简体   繁体   English

JSON有什么问题?

[英]What's wrong with my JSON?

Anybody out there notice anything wrong with this JSON? 有人注意到这个JSON有什么问题吗? It validates at JSONLint.com, but neither Chrome nor Firefox's native JSON parse functions will properly parse it. 它可以在JSONLint.com上进行验证,但是Chrome和Firefox的本机JSON解析功能都无法正确解析它。

Any ideas? 有任何想法吗?

{
        "result": "{\"players\":[{\"name\":\"User 522\",\"turn\":true,\"score\":0},{\"name\":\"User 925\",\"turn\":false,\"score\":5}],\"enableControls\":false}",
        "error": "null",
        "id": "7"
}

Even though you json looks kind of weird, it conforms with the json specification. 即使您的json看起来很奇怪,它也符合json规范。

You problem comes from an escaping problem when defining literals in Firefox or Chrome. 您的问题来自在Firefox或Chrome中定义文字时的转义问题。 The "\\" (backslash) character needs to be escaped with a backslash. “ \\”(反斜杠)字符需要用反斜杠转义。

Example 1: 范例1:

JSON.parse('{"key":"\""}'); breaks

Example 2: 范例2:

JSON.parse('{"key":"\\""}'); works

So JSONLint.com is right, and Firefox is right and Chrome is right also. 因此,JSONLint.com是正确的,Firefox是正确的,Chrome也是正确的。

You would not hit this problem if you were testing through an ajax request, because the escaping would be handled automatically. 如果通过ajax请求进行测试,则不会遇到此问题,因为转义将自动处理。 You are hitting the problem because you want to feed the json string as a literal (hence the need for escaping) 您遇到问题是因为您想将json字符串作为文字输入(因此需要转义)

I hope this will help you. 我希望这能帮到您。

I see now what is happening. 我现在知道发生了什么。 result is itself an embedded json string. result本身就是一个嵌入的json字符串。

Let me regroup and answer again. 让我重新组合并再次回答。

Your server is not doing you any favors here. 您的服务器在这里对您没有任何帮助。

Again, the string as given will NOT parse thus is not a valid JSON string. 同样,给定的字符串将不会解析,因此不是有效的JSON字符串。 And I don't see a way to massage it to get it to parse. 而且我没有办法按摩它以使其解析。

Are you SURE that this is the string that is being returned or perhaps this is a visualization of the string from a debugger? 您确定这是返回的字符串,或者这是调试器显示的字符串的可视化图像?

That is not valid JSON text, that is a somewhat mishappen JavaScript literal. 那不是有效的JSON文本,这是一种不太恰当的JavaScript文字。

You do not parse a literal, you parse text to obtain a literal. 您不解析文字,而是解析文本以获得文字。

Your literal would be better represented as... 您的文字会更好地表示为...

 
 
 
 
  
  
  var obj = { result: { players: [{ name: "User 522", turn: true, score: 0 }, { name: "User 925", turn: false, score: 5 }], enableControls: false }, error: null, id: 7 };
 
 
  

and this is the equivalent JSON text. 这是等效的JSON文本。 Try parsing this.. 尝试解析此。

 
 
 
 
  
  
  var json = '{"result":{"players":[{"name":"User522","turn":true,"score":0},{"name":"User925","turn": false,"score":5}],"enableControls":false},"error":null,"id":7}';
 
 
  

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

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