[英]How to escape double quotes in stringified object to PARSE IT into valid JSON?
我在 C# 中有一个列表。 在我的页面中,我给出了这个列表:'@Html.Raw(Json.Encode(Model.MyList))';
我把这个对象串起来,obj很好。
但是,当我尝试使用“JSON.parse”将其解析为对象 JSON 时,我有此异常“意外的令牌,在 JSON 中的位置 26 SyntaxError: Unexpected token,在 JSON 中的位置 26 处的 JSON.parse()”。
这是因为该对象的某些键中的双引号,例如“Example4”。
"Example2":"C01150",
"Example3":"C01150",
"Example4":"vase pompe de flèche ATC T 16"","
"Example5":false,"
},
我试过这个解决方案: https ://salesforce.stackexchange.com/questions/233068/replace-double-quotes-with-single-quote-in-a-json-string
还有这个: 如何在 JSON 中转义双引号
所以,我这样做: function jsonEscape(str) { return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g,"\\\\t").replace(/\\"/, '\\"');}
但是双引号不动...
JSON.parse 结果:
"Example4":"vase pompe de flèche ATC T 16"","
我正在尝试获取此代码:
"Example4": "vase pompe de flèche ATC T 16\"",
我想要一个有效的 JSON 对象。
有人能帮我吗 ?
正则表达式的最后一点,
replace(/\\"/, '\\"')
正在寻找序列\"
not "
如果读了,
replace(/"/g, '\"')
然后它将查找 " 的每个实例(全局g
"
并将其替换为对解析器安全的转义版本\"
。
尝试这个
var str = `{
"Example2":"C01150",
"Example3":"C01150",
"Example4":"vase pompe de flèche ATC T 16"","
"Example5":false
}`;
var arr = [];
var arrStr = str.replace("{", "").replace("}", "").split("\n");
arrStr.forEach((item) => {
arr.push(item.trim().split(":"));
});
str = "";
for (let index = 0; index < arr.length; index++) {
if (arr[index][1] == undefined) continue;
arr[index][1] = arr[index][1].replace('"",', "").replace(",", "");
console.log(arr[index][1]);
str = str + arr[index][0] + ":" + arr[index][1] + ",";
}
str = "{" + str.substring(0, str.length - 1) + "}";
console.log(JSON.parse(str));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.