JSON.stringify escaping without need
Solution 1
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"]}}}
Solution 2
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)
John
Updated on June 18, 2021Comments
-
John almost 3 years
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?
-
John almost 12 yearsFound the issue, the escaping was done by WordPress's esc_attr()
-
Benjamin Wen almost 7 years@Engineer , I don't know why this don't work well. Can you help me? I asked a question where I pasted the my code and everything. Thank you. stackoverflow.com/questions/45139583/…
-
halt00 over 6 yearsThis does not work. Copy and paste your code into jsbin.com and you get this. "\"{\\"2003\\":{\\"1\\":{\\"2\\":[\\"test\\"],\\"3\\":[\\"test2\\"]}}}\"" "{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}"
-
nthaxis over 5 yearsStill getting the escape chars for objects in jsbin