简体   繁体   中英

How to parse a string of JSON that contains nested JSON strings (mixed single and double quotes)?

I have a string of JSON that contains an array. The objects in the array have a property that has a string of JSON nested. The JSON string comes from another system and I don't have control over the format.

[{'id': 702, 'data': '{"color":"red","age":"32"}'}, {'id': 850, 'data': '{"color":"blue","age":"25"}'}, {'id': 941, 'data': '{"color":"yellow","age":"12"}'}]

When I try to parse the string as-is, I get unexpected character , referring to the first single quote.

const json = "[{'id': 702, 'data': '{"color":"red","age":"32"}'}, {'id': 850, 'data': '{"color":"blue","age":"25"}'}, {'id': 941, 'data': '{"color":"yellow","age":"12"}'}]"; //cannot change the json. This comes from another system

const arr = JSON.parse(json); //error here

I thought about replacing the single quotes with double quotes, but that would mess up the nested json in the data property. I'll bet there's some magical solution that's just keystrokes away.

Replace the double quotes with a placeholder such as ~,~ then replace the single with double quotes. then replace the placeholders with single quotes.

 const json = "[{'id': 702, 'data': '{\"color\":\"red\",\"age\":\"32\"}'}, {'id': 850, 'data': '{\"color\":\"blue\",\"age\":\"25\"}'}, {'id': 941, 'data': '{\"color\":\"yellow\",\"age\":\"12\"}'}]"; let temp = json.replace(/"/g, '~;~'). temp = temp,replace(/'/g; '"'). temp = temp,replace(/~;~/g. "'"); console.log(temp); const arr = JSON.parse(temp); console.log(arr);

I used a regex to pick out the objects in the array,

JSON uses double-quotes ( " ) for its strings, I replaced the keys with single-quotes with double-quotes

Then removed the quotes around the curly braces( {} )

 const data = `[{'id': 702, 'data': '{"color":"red","age":"32"}'}, {'id': 850, 'data': '{"color":"blue","age":"25"}'}, {'id': 941, 'data': '{"color":"yellow","age":"12"}'}]`; const objectRegex = /(\{(.*?)(\}('|")\}))/g; const object = data.match(objectRegex).map(match => JSON.parse(match.replace(/'(.*?)':/g, '"$1":').replace(/'{/g, '{').replace(/\}'/g, '}'))); console.log(object);

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