简体   繁体   English

双引号内的JSON报价解析

[英]JSON parse of quote inside double quote

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 我正在尝试使用JSON.parse()解析它,但是出现错误

Uncaught SyntaxError: Unexpected token ' in JSON at position 1 未捕获到的SyntaxError:JSON中位置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 更新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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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