Ωmega
Ωmega

Reputation: 43673

Why JSON.parse removes double quotes?

Having simple JS code:

var str = '[[[0,123,"John Doe"]],[[0,189,"Jane Doe, Mike Smith"]]]';
var obj = JSON.parse(str);
document.writeln(obj[1]);

Test it here

Why double quotes are removed? How can I force JS to not remove double quotes?


Or... how can I convert this JSON to array, having each element separated?

For example: obj[1][2] = "Jane Doe, Mike Smith"

Upvotes: 1

Views: 3520

Answers (1)

James M
James M

Reputation: 16718

If you want JSON to be printed, convert it back to JSON:

document.writeln(JSON.stringify(obj[1]));

By using JSON.parse, you convert the JSON into a real JavaScript array. There's no JSON in obj, and therefore no quotes.

If you want to manipulate the array, you can do this as you would any other array:

var str = '[[[0,123,"John Doe"]],[[0,189,"Jane Doe, Mike Smith"]]]';
var obj = JSON.parse(str);
obj[0][0][2] = "John Smith";

And then if you want your quotes back, you'll have to convert it back to JSON with JSON.stringify.

Upvotes: 4

Related Questions