Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which is correct - jsonlint or JSON.parse? [duplicate]

I have a javascript string in which a key has a value that is the string representation of an array:

{
  "a": "[\"b\",\"c\"]"
}

jsonlint.com says this is valid.

JSON.parse('{"a":"[\"b\",\"c\"]"}');

throws an error (unexpected token b at position 8). This seems to be about quotes containing escaped quotes - but my string seems to conform to the standard as per www.json.org.

// set up an object with this pattern
var o = {};
o['a'] = "[\"b\",\"c\"]";
console.dir(o.a); // -> "[\"b\",\"c\"]"

// look at the JSON string version of this object
var j = JSON.stringify(o);
console.dir(j); // -> {"a":"[\"b\",\"c\"]"}

// set up this inside a string and try to parse it
var k = '{"a":"[\"b\",\"c\"]"}';
var l = JSON.parse(k); // -> error

Who is correct? jsonlint.com or JSON.parse() ?

like image 467
frumbert Avatar asked May 11 '26 07:05

frumbert


1 Answers

When writing your string in javascript, you need to escape the \ characters or it's going to be interpreted.

const ret = JSON.parse('{"a":"[\\"b\\",\\"c\\"]"}');

console.log(ret);
like image 186
Orelsanpls Avatar answered May 13 '26 21:05

Orelsanpls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!