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);
Related
Following json string is not converting into json as key is not inside quote.
{file:"http://video.test.com/media/myvideo.mp4", image:"/category/dt/filename.png", width:"100%", height:"100%", stretching:"uniform", autostart:true, modes:[{type:"flash", src:"/swf/external/player.swf"}, {type:"html5"}]}
I have tried:
JSON.parse -- it does not work as keys are not inside quotes.
eval('('+str+')') -- not converting for some reason, also little reluctant for this solution due to security.
Manually insert double quotes delimiting colon (:) but one of my
value, which is a url, too has a colon, as given in the solution:
regular expression add double quotes around values and keys in javascript
Why is it difficult to convert this string into json and how to convert it?
var s = '{file:"http://video.test.com/media/myvideo.mp4", image:"/category/dt/filename.png", width:"100%", height:"100%", stretching:"uniform", autostart:true, modes:[{type:"flash", src:"/swf/external/player.swf"}, {type:"html5"}]}';
console.log(eval('(' + s + ')'));
The main question is really where did you get the string from, but anyways, here is a solution.
var obj = eval('(' + str + ')');
var json = JSON.stringify(obj);
How to convert this string into original array in Javascript?
var str_arr = "["myName","asldkfjs","2342","sbc#lkjsf.com","sdlkfjskldf",410]"
like I want to store it back as original array
var arr = ["myName","asldkfjs","2342","sbc#lkjsf.com","sdlkfjskldf",410];
You have a syntax error in your str_arr.
var str_arr = '["myName","asldkfjs","2342","sbc#lkjsf.com","sdlkfjskldf",410]';
var arr = JSON.parse(str_arr);
You could try parsing it as JSON, because an array is valid JSON (assuming it uses double quotes for the strings).
arr = JSON.parse(str_arr);
Also, as #manonthemat mentioned, you need to either use single quotes to wrap the string literal where you declare str_arr (since it contains double quotes) or you need to escape the double quotes to avoid a syntax error.
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 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) )();
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.