简体   繁体   English

如何使字符串兼容 JSON.parse()

[英]How to make string campatible for JSON.parse()

In my application when I enter value as my"name in text field the framework makes a String like ( this i can not control ):在我的应用程序中,当我在文本字段中输入值作为我的“名称”时,框架会生成一个类似的字符串(这是我无法控制的):

"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"

Now this String is passed to JSON.parse() method which produces an error because of ambiguous name field as现在这个字符串被传递给 JSON.parse() 方法,由于名称字段不明确而产生错误

\\"name\\":\\"my\\"name\\" \\"姓名\\":\\"我的\\"姓名\\"

var str = JSON.parse("[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]")

This results in JSON exception这会导致 JSON 异常

Is there anything I can do with the string:我可以对字符串做些什么:

"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"

To escape double quote character in my " name as my \\" name to make it valid for JSON.parse method.my " name as my \\" name双引号字符转义,使其对 JSON.parse 方法有效。

I can not control JSON String, I am just passing name as my"name and framework creates a String which is passed to JSON.parse()我无法控制 JSON 字符串,我只是将名称作为 my"name 传递,框架创建了一个传递给 JSON.parse() 的字符串

I went through a series of text replace.我经历了一系列的text替换。 You can try this:你可以试试这个:

var str = "[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]";

JSON.parse(
str.replace(/\\/i,"").
replace(/{"/g,"{'").
replace(/":"/g,"':'").
replace(/","/g,"','").
replace(/"}/g,"'}").
replace(/'/g,"\@@@").
replace(/"/g,"\\\"").
replace(/@@@/g,"\"")
);

It will give back your desired JSON array它将返回您想要的JSON数组

var str = "[{\"id\":\"201500000001002\"}]";
str.replace("\"*","\\\"");
var obj = JSON.parse(str);

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

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