带有ajax响应字符串的JSON解析错误

时间:2012-10-15 00:51:39

标签: javascript json

我一直在研究这个问题,我已经在网络和stackoverflow中搜索了解决方案,但是我无法确切地知道错误。

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

{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);
        }

请exaplin这里有什么错误。

感谢。

编辑:

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

1 个答案:

答案 0 :(得分:-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]