简体   繁体   English

JSON.stringify 无需转义

[英]JSON.stringify escaping without need

JSON.stringify is converting my json object to the following string JSON.stringify 正在将我的 json 对象转换为以下字符串

{\\"2003\\":{\\"1\\":{\\"2\\":[\\"test\\"],\\"3\\":[\\"test2\\"]}}} {\\"2003\\":{\\"1\\":{\\"2\\":[\\"test\\"],\\"3\\":[\\"test2\\"]}}}

When it should not be escaped.当它不应该被逃避时。 The result should be as the string quoted below结果应该是下面引用的字符串

{"2003":{"1":{"2":["test"],"3":["test2"]}}} {"2003":{"1":{"2":["test"],"3":["test2"]}}}

Rather than use a general replace of all the escaped quotes and remove ones that could be in the input.而不是使用所有转义引号的一般替换并删除可能在输入中的引号。 How can I set JSON.stringify to not double escape the variables?如何将 JSON.stringify 设置为不双重转义变量?

You are stringifying a string, not an object:您正在字符串化一个字符串,而不是一个对象:

var str = '{"2003":{"1":{"2":["test"],"3":["test2"]}}}';
var obj = {"2003":{"1":{"2":["test"],"3":["test2"]}}};

console.log( JSON.stringify(str) );  // {\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}} 
console.log( JSON.stringify(obj) );  // {"2003":{"1":{"2":["test"],"3":["test2"]}}} 

Try these two examples in browser`s console:在浏览器的控制台中尝试这两个示例:

let obj = {2003:{1:{2:["test"],3:["test2"]}}};
JSON.stringify(obj);

-> "{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}"

and

let obj = {2003:{1:{2:["test"],3:["test2"]}}};
console.log(JSON.stringify(obj));

-> {"2003":{"1":{"2":["test"],"3":["test2"]}}}

In both cases the string returned from JSON.stringify is valid在这两种情况下,JSON.stringify返回字符串都是有效的

In the first case you print "raw" string to console which starts and ends with double quote and all nested double quotes need to be escaped ( \\" instead of " ).在第一种情况下,您将“原始”字符串打印到以双引号开头和结尾的控制台,并且所有嵌套的双引号都需要转义( \\"而不是" )。 JSON validators will mark this string as malformed JSON but it is still parsable with JSON.parse JSON 验证器会将这个字符串标记为格式错误的 JSON,但它仍然可以用JSON.parse解析

In the second case you print string "interpreted" as JSON by console.log .在第二种情况下,您通过console.log字符串“解释”打印为 JSON JSON validators will mark it as valid JSON but it is no parsable with JSON.parse because it is not string (no quotes around) JSON 验证器会将其标记为有效的 JSON,但无法使用JSON.parse解析,因为它不是字符串(周围没有引号)

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

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