I have a string
str = "{'a':1}";
JSON.parse(str);
VM514:1 Uncaught SyntaxError: Unexpected token '(…)
How can I parse the above string (str) into a JSON object ?
This seems like a simple parsing. It's not working though.
The JSON standard requires double quotes and will not accept single quotes, nor will the parser.
If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"') and you should end up with valid JSON.
I know it's an old post, but you can use JSON5 for this purpose.
<script src="json5.js"></script>
<script>JSON.stringify(JSON5.parse('{a:1}'))</script>
If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.
var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');
The extra parentheses are required due to how the eval parser works.
Eval is not evil when it is used on data you have control over.
For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()
Using single quotes for keys are not allowed in JSON. You need to use double quotes.
For your use-case perhaps this would be the easiest solution:
str = '{"a":1}';
Source:
If a property requires quotes, double quotes must be used. All
property names must be surrounded by double quotes.
var str = "{'a':1}";
str = str.replace(/'/g, '"')
obj = JSON.parse(str);
console.log(obj);
This solved the problem for me.
Something like this:
var div = document.getElementById("result");
var str = "{'a':1}";
str = str.replace(/\'/g, '"');
var parsed = JSON.parse(str);
console.log(parsed);
div.innerText = parsed.a;
<div id="result"></div>
// regex uses look-forwards and look-behinds to select only single-quotes that should be selected
const regex = /('(?=(,\s*')))|('(?=:))|((?<=([:,]\s*))')|((?<={)')|('(?=}))/g;
str = str.replace(regex, '"');
str = JSON.parse(str);
The other answers simply do not work in enough cases. Such as the above cited case: "title": "Mama's Friend", it naively will convert the apostrophe unless you use regex. JSON5 will want the removal of single quotes, introducing a similar problem.
Warning: although I believe this is compatible with all situations that will reasonably come up, and works much more often than other answers, it can still break in theory.
sometimes you just get python data, it looks a little bit like json but it is not. If you know that it is pure python data, then you can eval these data with python and convert it to json like this:
echo "{'a':1}" | /usr/bin/python3 -c "import json;print(json.dumps(eval(input())))"
Output:
{"a": 1}
this is good json.
if you are in javascript, then you could use JSON.stringify like this:
data = {'id': 74,'parentId': null};
console.log(JSON.stringify(data));
Output:
> '{"id":74,"parentId":null}'
If you assume that the single-quoted values are going to be displayed, then instead of this:
str = str.replace(/\'/g, '"');
you can keep your display of the single-quote by using this:
str = str.replace(/\'/g, '\'\');
which is the HTML equivalent of the single quote.
json = ( new Function("return " + jsonString) )();
Related
How do I parse an array of objects if it contains single quote characters?
For example, I have:
$example = '{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}';
The single quotes seem to break up the array, making parsing impossible.
You can use backticks (``). It will generate the string as it was written, with double "" and single ' quotes.
var str = `{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}`;
console.log(str);
var obj = JSON.parse(str);
console.log(obj.response[0].uid);
It's a json string not an object.
Use JSON.parse(myJsonSting) and you will get objects with the ' taken care of.
Javascript is supposed to ignore single quotes if it is inside double quotes, in your case try adding backslash before the single quote.
To parse at json string to object
var example = '{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}';
var objExample = JSON.parse(example);
To convert json object to json string
var StrExample = JSON.stringify(objExample);
this is my string,
var str=""{\"checkedRows\":\"[{\"SlNo\":\"1\",\"ItemCode\":\"8\",\"ItemDetail\":\"Cassue Nut\",\"Qty\":\"140\",\"Rate\":\"2000\",\"Amount\":280000\"}]\",\"checkedIndex\":\"[0]\"}"";
I'm trying to get substring as below
[{\"SlNo\":\"1\",\"ItemCode\":\"8\",\"ItemDetail\":\"Cassue Nut\",\"Qty\":\"140\",\"Rate\":\"2000\",\"Amount\":280000\"}]
And i'm trying below code to split
var newStr = str.substring(str.lastIndexOf("[") + 1, str.lastIndexOf("]"))
but unable to fetch it.
Firstly note that you have an extra leading and trailing double quote around your JSON string. Secondly the JSON itself is completely malformed. You need to fix the errors it has (extra/mis-matched double quotes mostly) so it looks like this:
'{"checkedRows":[{"SlNo":"1","ItemCode":"8","ItemDetail":"Cassue Nut","Qty":"140","Rate":"2000","Amount":280000}],"checkedIndex":[0]}'
Once you've done that you can parse the string to an object, then retrieve the checkedRows property and stringify that again, like this:
var str = '{"checkedRows":[{"SlNo":"1","ItemCode":"8","ItemDetail":"Cassue Nut","Qty":"140","Rate":"2000","Amount":280000}],"checkedIndex":[0]}';
var obj = JSON.parse(str);
var newStr = JSON.stringify(obj.checkedRows);
console.log(newStr);
I have string which is in form of JSON but not a valid JSON string. String is like as below (Its single line string but I have added new lines for clarity.)
"{
clientId :\"abc\",
note:\"ATTN:Please take care of item x\"
}"
I am trying to fix it (reformating to valid JSON) using javascript regular expression. I am currently using following regular expression but its not working for second property i.e. note as it has colon (:) in its value.
retObject.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2": ');
What I am trying to do here is using regular expression to reformat above string to
"{
"clientId" :"abc",
"note":"ATTN:Please take care of item x"
}"
Tried many ways but couldnt get it just right as I am still beginer in RegEx.
Try using .split() with RegExp /[^\w\s\:]/ , .test() with RegExp /\:$/ , .match() with RegExp /\w+/
var str = "{clientId :\"abc\",note:\"ATTN:Please take care of item x\"}";
var res = {};
var arr = str.split(/[^\w\s\:]/).filter(Boolean);
for (var i = 0; i < arr.length; i++) {
if ( /\:$/.test(arr[i]) ) {
res[ arr[i].match(/\w+/) ] = arr[i + 1]
}
}
console.log(res)
Trying to fix broken JSON with a regexp is a fool's errand. Just when you think you have the regexp working, you will be presented with additional gobbledygook such as
"{ clientId :\"abc\", note:\"ATTN:Please take \"care\" of item x\" }"
where one of the strings has double quotes inside of it, and now your regexp will fail.
For your own sanity and that of your entire team, both present and future, have the upstream component that is producing this broken JSON fixed. All languages in the world have perfectly competent JSON serializers which will create conformant JSON. Tell the upstream folks to use them.
If you have absolutely no choice, use the much-reviled eval. Meet evil with evil:
eval('(' + json.replace(/\\"/g, '"') + ')')
We're already aware that we cannot add double quotes inside the double quotes:
var str = ""hello""; //this will be invalid string
but when I stringify an object like this
var obj = {"name":"abc"}
var str = JSON.stringify(obj).
str // returns "{"name":"abc"}"
which is valid but shouldn't be. I'm confused as in do JavaScript have some special cases when we stringify a JSON object and omit the string validations on it?
Thanks in advance.
You can have as many double quotes inside a string literal as you want. You just need to scape them using a backslash prefix (\" instead of ").
Try this example in your browser console:
var myStr = "\"Hello\"";
myStr
You should see ""Hello"" in your console. That would be how the stringify creates a string with double quotes in it.
I have a project, in which some JavaScript var is evaluated. Because the string needs to be escaped (single quotes only), I have written the exact same code in a test function. I have the following bit of pretty simple JavaScript code:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
// Here, the string needs to be escaped for single quotes for the eval
// to work as is. The following does NOT work! Help!
strInputString.replace(/'/g, "''");
var strTest = "strResult = '" + strInputString + "';";
eval(strTest);
alert(strResult);
}
And I want to alert it, saying: fsdsd'4565sd.
The thing is that .replace() does not modify the string itself, so you should write something like:
strInputString = strInputString.replace(...
It also seems like you're not doing character escaping correctly. The following worked for me:
strInputString = strInputString.replace(/'/g, "\\'");
Best to use JSON.stringify() to cover all your bases, like backslashes and other special characters. Here's your original function with that in place instead of modifying strInputString:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
var strTest = "strResult = " + JSON.stringify(strInputString) + ";";
eval(strTest);
alert(strResult);
}
(This way your strInputString could be something like \\\'\"'"''\\abc'\ and it will still work fine.)
Note that it adds its own surrounding double-quotes, so you don't need to include single quotes anymore.
I agree that this var formattedString = string.replace(/'/g, "\\'"); works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.
The solution that worked for me is that you need to put three \ and escape the double quotes.
"var string = \"l'avancement\";
var formattedString = string.replace(/'/g, \"\\\'\");"
I answer that question since I had trouble finding that three \ was the work around.
Only this worked for me:
searchKeyword.replace(/'/g, "\\\'");//searchKeyword contains "d'av"
So, the result variable will contain "d\'av".
I don't know why with the RegEx didn't work, maybe because of the JS framework that I'm using (Backbone.js)
That worked for me.
string address=senderAddress.Replace("'", "\\'");
There are two ways to escaping the single quote in JavaScript.
1- Use double-quote or backticks to enclose the string.
Example: "fsdsd'4565sd" or `fsdsd'4565sd`.
2- Use backslash before any special character, In our case is the single quote
Example:strInputString = strInputString.replace(/ ' /g, " \\' ");
Note: use a double backslash.
Both methods work for me.
var str ="fsdsd'4565sd";
str.replace(/'/g,"'")
This worked for me. Kindly try this
The regular expression in the following code also handles the possibility of escaped single quotes in the string - it will only prepend backslashes to single quotes that are not already escaped:
strInputString = strInputString.replace(/(?<!\\)'/g, "\\'");
Demo: https://regex101.com/r/L1lF7J/1
Compatibility
The regex above uses negative lookbehind, which is widely supported but if using an older Javascript version, this clunkier regex (which uses a capturing group backreference instead) will also do the job:
strInputString = strInputString.replace(/(^|[^\\])'/g, "$1\\'");
Demo: https://regex101.com/r/9niyYw/1
strInputString = strInputString.replace(/'/g, "''");