简体   繁体   中英

Convert string to JSON object in Javascript

I have a string in this format:

var abc = "{'ABC':'25117', 'data':'India\"NewDelhi\"'}"

I want to convert this to a JSON object.

I've tried to use "" and '' by interchanging them.

I've used the function JSON.parse(abc) , it works if the string

var abc = '{"ABC":"25117", "data":"India\'NewDelhi\'"}'

But I want that "NewDelhi" should be in double quotes ie "" and this is my strict condition.

Stick with valid JSON, and just double escape the quotes

var abc = '{"ABC":"25117", "data":"India\\"NewDelhi\\""}';

FIDDLE

You have to escape "\\" to be able to parse your string.

var abc = "{\"ABC\":\"25117\", \"data\":\"India\\\"NewDelhi\\\"\"}"

Then JSON.parse(abc) will works

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