My value is a string:
"['Eitaj', 'Jason Json', 'Eitaj M', "Jason Json's"]"
I am trying to parse it using JSON.parse()
, however, I get error
Uncaught SyntaxError: Unexpected token ' in JSON at position 1
I find out the the working correct string is:
JSON.parse('["Eitaj", "Jason Json", "Eitaj M", "Jason Json\'s"]')
Is there any trick I can use other than placing single quotes with double quotes?
Check whether this works for you.
let s = "['Eitaj', 'Jason Json', 'Eitaj M', \\"Jason Json's\\"]"; let parsed = JSON.parse(s.split(",").map(seg => { return seg.replace(new RegExp("'.*'", "g"), function(match) { return '"' + match.substring(1, match.length - 1) + '"'; }) }).join(",")); console.log(parsed);
Update 1
This will handle flaws of the above snippet which are mentioned in the comments. However there can be still other edge cases which should be handled based on your requirement.
let s = "['Eitaj', 'Jason Json', 'Eitaj M', \\"Jason Json's\\",\\"Test'test'Test\\",'Acme, Inc.',\\"'Test'\\"]"; let parsed = JSON.parse("[" + s.substring(1, s.length - 1).match(new RegExp(`((['\\""]).*?(\\\\2))`, "g")).map(seg => { return seg.trim().replace(new RegExp("^'.*'$", "g"), function(match) { return '"' + match.substring(1, match.length - 1) + '"'; }) }).join(",") + "]") console.log(parsed);
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.