简体   繁体   中英

Escaping quotation marks from string in javascript

I am trying to create a json

var str  = '{"name": "Sam", "address": [{"street": "Main St"}, {"street": "2nd Street"}]}';

Now to remove the double quotes from value of address, I do

var street = '[{"street": "Main St"}, {"street": "2nd Street"}]';

street = street.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');

str = '{"name": "Sam", "address": "'+street+'"}'

which gives

{"name": "Sam", "address": "[{\"street\": \"Main St\"}, {\"street\": \"2nd Street\"}]"}"

But if i do JSON.stringify(str) , I end up with

"{\"name\": \"Sam\", \"address\": \"[{\\\"street\\\": \\\"Main St\\\"}, {\\\"street\\\": \\\"2nd Street\\\"}]\"}

My question is, what is the right way to escape double quotes from a JSON string.

why not create an object, as opposed to a string?

var obj   = {name: "Sam", address: [{street: "Main St"}, {street: "2nd Street"}]};
JSON.stringify(obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM