JSON.stringify escaping without need

47,561

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)

Share:
47,561
John
Author by

John

Updated on June 18, 2021

Comments

  • John
    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
    John almost 12 years
    Found the issue, the escaping was done by WordPress's esc_attr()
  • Benjamin Wen
    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
    halt00 over 6 years
    This does not work. Copy and paste your code into jsbin.com and you get this. "\"{\\"2003\\":{\\"1\\":{\\"2\\":[\\"test\\"],\\"3\\":[\\"te‌​st2\\"]}}}\"" "{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}"
  • nthaxis
    nthaxis over 5 years
    Still getting the escape chars for objects in jsbin