带有反斜杠的JSON解析错误 [英] JSON Parsing error with backslash

查看:1456
本文介绍了带有反斜杠的JSON解析错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图弄清为什么以下JSON输入将无法在JSON.parse函数中进行解析.

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

上面的json由JSON.NET返回.

我尝试了多种方法来使其正常工作.如您所见,反斜杠已转义,并且 https://jsonlint.com/可以对其进行解析.

我在 https://jsfiddle.net/ckp0uc0p/3/上有一个失败的示例也是

任何帮助将不胜感激.

解决方案

将JSON注入JavaScript 源代码的最佳方法(当使用服务器端语言生成JavaScript时)是注入它直接在您需要的位置,而不是在需要解析的字符串文字中.

例如:

var foo = <json blob>;

这样结果将是

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

JavaScript会将其解释为对象文字,从而产生一个 object ,无论如何,这都是您想要得到的.这样可以避免嵌套"转义序列带来的所有问题.

I have been trying to figure out why the following JSON input will be failed to parse in JSON.parse function.

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

The json above is being returned by 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.

I have a failing sample at https://jsfiddle.net/ckp0uc0p/3/ as well.

Any help will be appreciated.

解决方案

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.

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. This avoids all the problems with "nested" escape sequences.

这篇关于带有反斜杠的JSON解析错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆