Ball
现在var str = '{"Language":"en","Type":"General","Text":""Mela" means "apple" in Italian"}';
会抛出此错误
JSON.parse(str)
现在替换引号会转义整个字符串,并且已解析的JSON不再可用
Uncaught SyntaxError: Unexpected token M in JSON at position 43
str = str.replace(/\\([\s\S])|(")/g,"\\$1$2");
以下其他解决方案似乎无法在此方案中使用
How to escape a JSON string containing newline characters using JavaScript?
答案 0 :(得分:0)
您需要在字符串中的每个双引号之前添加反斜杠:
const str = '{"Language":"en","Type":"General","Text": "\\"Mela\\" means \\"apple\\" in Italian"}';
const obj = JSON.parse(str)
console.log(obj.Text)
答案 1 :(得分:0)
在JSON中,你不要逃避属性名称的双引号或属性值的乞讨,只要逃避属性值内的内容:
{\"Text\":\"\"Mela\" means ....
应该是这样的:
{"Text":"\"Mela\" means ....
答案 2 :(得分:0)
这可以通过多次替换来完成:
var str = '{"Language":"en","Type":"General","Text":""Mela" means "apple" in Italian"}';
str = str.replace(/"/,"'"); //Replace all " with '
str = str.replace(/{'/,'{"') //Restore " to start of JSON
str = str.replace(/','/,'","'); //Restore " around JSON , separators
str = str.replace(/':'/,'":"'); //Restore " around JSON : separators
str = str.replace(/'}/,'"}'); //Restore " to end of JSON
str = str.replace(/'/,'\"'); //All remaining ' must be inside of data, so replace with properly escaped \"
console.log(str);
编辑:此解决方案的一个问题是,它还将替换文本中的原始“字符”。