1

我一直在研究这个问题,我已经在 web 和 stackoverflow 中搜索了解决方案,但我无法准确了解错误。

这是通过 ajax 调用来自服务器的 json 字符串。

{root:{name: "root",description: "root description",checked: false,1:{name: "item1",description: "item1 description",checked: true,1.1:{name: "item1.1",description: "item1.1 description",checked: true}}, 2:{name: "item2",description: "item2 description",checked: true}}}

使用下面的代码我得到字符串之后xmlhttp.readyState == 4 && xmlhttp.status == 200

var aData;
        try{
        aData =JSON.parse(xmlhttp.responseText);
        }
        catch(err){
        alert(err);
        }

它显示了类似的错误

Json.parse expected property name or '}'

但如果使用 eval() 函数它工作正常

var aData;
        try{
        aData =eval('(' + xmlhttp.responseText + ')');
        }
        catch(err){
        alert(err);
        }

请解释这里的错误是什么。

谢谢。

编辑:

我已经检查了 json 查看器中的字符串,它工作正常。http://jsonviewer.stack.hu/"> JSON 视图

4

1 回答 1

-1

那是因为那是无效的 JSON,你不能使用数字作为键名。因此,您可以跳过数字或将它们放在引号中,以便它们成为“字符串”。

验证器输出和固定的 JSON 如下:

固定的 JSON:

{
   "root":{
      "name":"root",
      "description":"root description",
      "checked":false,
      "1":{
         "name":"item1",
         "description":"item1 description",
         "checked":true,
         "1.1":{
            "name":"item1.1",
            "description":"item1.1 description",
            "checked":true
         }
      },
      "2":{
         "name":"item2",
         "description":"item2 description",
         "checked":true
      }
   }
}

验证器输出:

Error:Strings should be wrapped in double quotes.[Code 17, Structure 2]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 5]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 9]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 13]
Error:Expecting string, not number.[Code 8, Structure 17]
Error:Expecting comma or }, not colon.[Code 13, Structure 18]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 20]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 24]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 28]
Error:Expecting string, not number.[Code 8, Structure 32]
Error:Expecting comma or }, not colon.[Code 13, Structure 33]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 35]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 39]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 43]
Error:Expecting string, not number.[Code 8, Structure 49]
Error:Expecting comma or }, not colon.[Code 13, Structure 50]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 52]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 56]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 60]
于 2012-10-15T03:53:23.177 回答