简体   繁体   English

带反斜杠的JSON解析错误

[英]JSON Parsing error with backslash

I have been trying to figure out why the following JSON input will be failed to parse in JSON.parse function. 我一直试图弄清楚为什么以下JSON输入将无法在JSON.parse函数中解析。

{"World":"Hello\\Test"}

The json above is being returned by JSON.NET. 上面的json是由JSON.NET返回的。

I have tried multiple methods to get this working. 我已经尝试了多种方法来实现这一点。 As you can see the backslash is escaped and https://jsonlint.com/ is able to parse it. 如您所见,反斜杠已转义, https ://jsonlint.com/可以解析它。

I have a failing sample at https://jsfiddle.net/ckp0uc0p/3/ as well. 我在https://jsfiddle.net/ckp0uc0p/3/上也有一个失败的样本。

Any help will be appreciated. 任何帮助将不胜感激。

You need to add two \\\\ for every backslash you want to have it displayed. 您需要为要显示的每个反斜杠添加两个\\\\ If you're parsing a json, to display 2 backslashes you need to add 4. 如果要解析json,要显示2个反斜杠,则需要添加4个。

 // inside a string to be parsed as json var json = '{"World":"Hello\\\\\\\\Test"}' console.log(JSON.parse(json)) // directly in an object var object = {"World": "Hello\\\\Test"} console.log(object) 

The best way to inject JSON into JavaScript source code (when generating the JavaScript with a server side language), is to inject it directly where you need it, not inside a string literal that needs to be parsed. 将JSON注入JavaScript 源代码 (使用服务器端语言生成JavaScript)的最佳方法是将其直接注入到需要它的位置,而不是在需要解析的字符串文本中。

For example: 例如:

var foo = <json blob>;

so that the result will be 这样结果就会如此

var foo = {"World":"Hello\\Test"};

JavaScript will interpret this as an object literal resulting in an object , which is what you want to get anyway. JavaScript会将此解释为一个对象文字,从而产生一个对象 ,无论如何都是你想要获得的对象 This avoids all the problems with "nested" escape sequences. 这避免了“嵌套”转义序列的所有问题。

 try { var res = '{"World":"Hello\\\\\\\\Test"}'; var s = JSON.parse(res); console.log(JSON.stringify(s)); } catch(error) { alert(error); } 

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

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