javascript 使用转义引号解析 JSON 时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30114429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:43:17  来源:igfitidea点击:

Error Parsing JSON with escaped quotes

javascriptjson

提问by casillas

I am getting the following json object when I call the URL from Browser which I expect no data in it.

当我从浏览器调用 URL 时,我得到以下 json 对象,我希望其中没有数据。

"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"

However, when I tried to call it in javascript it gives me error Parsing Json message

但是,当我尝试在 javascript 中调用它时,它给了我 error Parsing Json message

dspservice.callService(URL, "GET", "", function (data) {
    var dataList = JSON.parse(data);
)};

This code was working before I have no idea why all of a sudden stopped working and throwing me error.

在我不知道为什么突然停止工作并抛出错误之前,此代码正在工作。

采纳答案by Tim Biegeleisen

Since there is nothing wrong with the JSON string you gave us, the only other explanation is that the databeing passed to your function is something otherthan what you listed.

由于没有什么错,你给我们的JSON字符串,唯一的解释是,data传递给你的函数存在的东西其他比你列出的东西。

To test this hypothesis, run the following code:

要测试此假设,请运行以下代码:

dspservice.callService(URL, "GET", "", handler(data));

function handler(data) {
    var goodData = "{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}";
    alert(goodData);                         // display the correct JSON string
    var goodDataList = JSON.parse(goodData); // parse good string (should work)
    alert(data);                             // display string in question
    var dataList = JSON.parse(data);         // try to parse it (should fail)
}

If the goodDataJSON string can be parsed with no issues, and dataappears to be incorrectly-formatted, then you have the answer to your question.

如果goodData可以毫无问题地解析 JSON 字符串,并且data看起来格式不正确,那么您的问题就有答案了。

Place a breakpoint on the first line of the handlerfunction, where goodDatais defined. Then step through the code. From what you told me in your comments, it is still crashing during a JSON parse, but I'm willing to wager that it is failing on the secondparse and not the first.

handlergoodData定义的函数的第一行上放置一个断点。然后逐步执行代码。根据您在评论中告诉我的内容,它在 JSON 解析期间仍然崩溃,但我愿意打赌它在第二次解析而不是第一次解析中失败。

回答by Tim Biegeleisen

You say the server is returning the JSON (omitting the enclosing quotes):

您说服务器正在返回 JSON(省略引号):

{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}

This is invalid JSON. The quote marks in JSON surrounding strings and property names should notbe preceded by a backslash. The backslash in JSON is strictly for inserting double quote marks insidea string. (It can also be used to escape other characters inside strings, but that is not relevant here.)

这是无效的 JSON。在JSON字符串周围和属性名引号应该不是一个反斜杠。JSON 中的反斜杠严格用于字符串中插入双引号。(它也可用于转义字符串中的其他字符,但这与此处无关。)

Correct JSON would be:

正确的 JSON 将是:

{"data":[], "SkipToken":"", "top":""}

If your server returned this, it would parse correctly.

如果您的服务器返回此信息,它将正确解析。

The confusion here, and the reports by other posters that it seems like your string should work, lies in the fact that in a simple-minded test, where I type this string into the console:

这里的混乱,以及其他海报的报告,似乎你的字符串应该可以工作,在于在一个简单的测试中,我在控制台中输入这个字符串:

var x = "{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}";

the JavaScript string literal escaping mechanism, which is entirely distinct from the use of escapes in JSON, results in a string with the value

JavaScript字符串文字逃逸机制,这是从在字符串中使用JSON逃逸,结果用值完全不同

{"data":[], "SkipToken":"", "top":""}

which of course JSON.parse can handle just fine. But Javascript string escaping applies to string literals in source code, not to things coming down from the server.

当然 JSON.parse 可以处理得很好。但是 Javascript 字符串转义适用于源代码中的字符串文字,而不是来自服务器的内容。

To fix the server's incorrectly-escaped JSON, you have two possibilities. One is to tell the server guys they don't need to (and must not) put backslashes before quote marks (except for quote marks insidestrings). Then everything will work.

要修复服务器错误转义的 JSON,您有两种可能性。一个是要告诉他们不需要到服务器的家伙(且不能)把前引号反斜杠(除引号的字符串)。然后一切都会好起来的。

The other approach is to undo the escaping yourself before handing it off to JSON.parse. A first cut at this would be a simple regexp such as

另一种方法是在将其交给JSON.parse. 第一个切入点是一个简单的正则表达式,例如

data.replace(/\"/g, '"')

as in

var dataList = JSON.parse(data.replace(/\"/g, '"')

It might need additional tweaking depending on how the server guys are escaping quotes inside strings; are they sending \"\\"\", or possibly \"\\\"\"?

根据服务器人员如何转义字符串中的引号,它可能需要额外的调整;他们正在发送\"\\"\",还是可能发送\"\\\"\"

I cannot explain why this code that was working suddenly stopped working. My best guess is a change on the server side that started escaping the double quotes.

我无法解释为什么这段正在工作的代码突然停止工作。我最好的猜测是服务器端的更改开始转义双引号。

回答by Leo

Did you mean that your JSON is like this?

你的意思是你的JSON是这样的吗?

"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"

Then datain your callback would be like this:

然后data在你的回调中会是这样的:

'"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"'

Because datais the fetched text content string.

因为data是获取的文本内容字符串。

You don't have to add extra quotes in your JSON:

您不必在 JSON 中添加额外的引号:

{"data":[], "SkipToken":"", "top":""}