31

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
  • 5,942
  • 3
  • 42
  • 79

2 Answers2

49

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"]}}} 
Engineer
  • 47,849
  • 12
  • 88
  • 91
  • 1
    Found the issue, the escaping was done by WordPress's esc_attr() – John Jun 10 '12 at 08:04
  • @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. https://stackoverflow.com/questions/45139583/how-can-i-construct-a-post-request-body-in-react-native-not-with-a-stringified-j – wzso Jul 17 '17 at 08:50
  • 9
    This 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\"]}}}" – halt00 Oct 05 '17 at 14:25
  • 5
    Still getting the escape chars for objects in jsbin – nthaxis Oct 26 '18 at 20:54
7

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)

OdkoPP
  • 442
  • 6
  • 14