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.
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);
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);
In my application when I enter value as my"name in text field the framework makes a String like (this i can not control):
"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"
Now this String is passed to JSON.parse() method which produces an error because of ambiguous name field as
\"name\":\"my\"name\"
var str = JSON.parse("[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]")
This results in JSON exception
Is there anything I can do with the string:
"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"
To escape double quote character in my " name as my \" name to make it valid for JSON.parse method.
I can not control JSON String, I am just passing name as my"name and framework creates a String which is passed to JSON.parse()
I went through a series of text replace. You can try this:
var str = "[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]";
JSON.parse(
str.replace(/\\/i,"").
replace(/{"/g,"{'").
replace(/":"/g,"':'").
replace(/","/g,"','").
replace(/"}/g,"'}").
replace(/'/g,"\###").
replace(/"/g,"\\\"").
replace(/###/g,"\"")
);
It will give back your desired JSON array
var str = "[{\"id\":\"201500000001002\"}]";
str.replace("\"*","\\\"");
var obj = JSON.parse(str);
JSON.stringify is converting my json object to the following string
{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}
When it should not be escaped. The result should be as the string quoted below
{"2003":{"1":{"2":["test"],"3":["test2"]}}}
Rather than use a general replace of all the escaped quotes and remove ones that could be in the input. How can I set JSON.stringify to not double escape the variables?
You are stringifying a string, not an object:
var str = '{"2003":{"1":{"2":["test"],"3":["test2"]}}}';
var obj = {"2003":{"1":{"2":["test"],"3":["test2"]}}};
console.log( JSON.stringify(str) ); // {\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}
console.log( JSON.stringify(obj) ); // {"2003":{"1":{"2":["test"],"3":["test2"]}}}
Try these two examples in browser`s console:
let obj = {2003:{1:{2:["test"],3:["test2"]}}};
JSON.stringify(obj);
-> "{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}"
and
let obj = {2003:{1:{2:["test"],3:["test2"]}}};
console.log(JSON.stringify(obj));
-> {"2003":{"1":{"2":["test"],"3":["test2"]}}}
In both cases the string returned from JSON.stringify is valid
In the first case you print "raw" string to console which starts and ends with double quote and all nested double quotes need to be escaped (\" instead of "). JSON validators will mark this string as malformed JSON but it is still parsable with JSON.parse
In the second case you print string "interpreted" as JSON by console.log. JSON validators will mark it as valid JSON but it is no parsable with JSON.parse because it is not string (no quotes around)