2016-01-21 116 views
1
$.getJSON("hello.txt", function(json) { 
    console.log(json); 
    alert(json.rgInventory[2].id); 
}); 

使用下面的代码我试图从hello.txt文件中解析JSON信息并显示它。正如你所看到的,代码下的图片能够正确识别JSON信息,但是当试图从第三个元素打印出它的rgInventory对象时,它说未定义。JSON解析问题undefined

enter image description here

有这一个与信息内许多对象,并都有一个ID。我正在使用的JSON数据可以在这里找到:http://steamcommunity.com/id/flaangvik/inventory/json/730/2

+1

请张贴在请求返回的JSON。 –

+0

尝试console.log(json.rgInventory); –

+0

这是json - > http://steamcommunity.com/id/flaangvik/inventory/json/730/2 –

回答

1

问题是因为在JSON响应中rgInventory是一个对象,而不是一个数组。

我试图环通,并从每个对象获得该对象

在这种情况下,你需要通过对象迭代里面的ID。试试这个:

$.getJSON("hello.txt", function(json) { 
    $.each(json.rgInventory, function(key, obj) { 
     console.log(obj); 
     var id = obj.id; 
     // work with each object here... 
    }) 
}); 
+0

谢谢,将“foo”改为“json”并且工作正常! :) –

0

试试这些代码: -

$(json.rgInventory).each(function(key, value){ 
    console.log(value); 
    // Do your code here 
}); 
0

根据您的JSON回报,从你的回报rgInventory属性是一个对象而不是数组。您可能需要使用散列键而不是索引号来访问子项。

JSON:

{"success":true,"rgInventory":{"4847011145":{"id":"4847011145","classid":"506870401","instanceid":"188530398","amount":"1","pos":1},"4846997498":{"id":"4846997498","classid":"653322524","instanceid":"188530248","amount":"1","pos":2},... 

你应该写:

$.getJSON("hello.txt", function(json) { 
alert(json.rgInventory["4847011145"].id); 
}