简体   繁体   中英

JSON parsing problems undefined

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

Using the following code I am trying to parse JSON information from an hello.txt file, and display it. As you can see inn the picture under the code recognizes the JSON information correctly but when trying to print the id from the third element it the rgInventory object, it says undefined.

在此处输入图片说明

There is many objects inside this one with information and all have an ID. The JSON data I'm working with is available here: http://steamcommunity.com/id/flaangvik/inventory/json/730/2

The issue is because in the JSON response rgInventory is an object, not an array.

I am trying to loop thru and get id from each object inside that object

In this case you need to iterate through the object. Try this:

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

Try these code :-

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

According to your JSON return, the rgInventory property from your return is an object instead of an array. You might need to access the child by the hash key instead of an index number.

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},...

You should write:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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