0

I have this json file. It's actually a steam inventory.

I want to parse this in Javascript or JQuery.

I tried this:

var jsonSteam = JSON.parse(jsonStringhere);
alert("ICON " + jsonSteam.rgDescriptions);

This alerts me "Icon [object,OBJECT]" how can loop trough all the descriptions and get the icon_url?

I tried to get a single element using alert("ICON " + jsonSteam.rgDescriptions[0].icon_url); but this doesn't work.

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
SKSKSKS
  • 5
  • 2
  • just `console.log(jsonSteam.rgDescriptions)` to see the structure of parsed json, there are another "keys" no 0,1,2, etc. – rafwlaz Dec 12 '16 at 23:16
  • I went to your pastebin, opened my Chrome browser js console, and did `var inv = JSON.parse($('div.de1').text())` then `inv` and got a navigable display of the variable. Your `JSON.parse` is working fine. —— when you use either alert or console.log and you add `String + Object` like your `"ICON " + jsonSteam ...` the result is coerced to a String, so you don't see your object members. – Stephen P Dec 12 '16 at 23:21
  • thank you everyone. Works like this. – SKSKSKS Dec 13 '16 at 03:19

1 Answers1

0

If you change your alert to just alert(jsonSteam.rgDescriptions), you will be able to see the object structure. You aren't seeing it now because you are concatenating it to a message ("ICON"). However, the fact that you do see [object,OBJECT] means that the returned object does have an rgDescriptions property and that property is storing an object. But, if there is an object there, you wouldn't retrieve its properties with an index [0] (which you could do with an array). You would retrieve it with the property name.

Looping will depend on the structure and how deep you need to go. Here's an example:

var jsonStream = {
  rgDescriptions: {
    somePropertyName : "some value",
    someOtherPropertyName : 66
  }
};

// Test to see the object structure:
console.log(jsonStream);

// Loop through the object
for(var prop in jsonStream.rgDescriptions){
  console.log("The " + prop + " property has a value of: " + jsonStream.rgDescriptions[prop]);
}

// Or, a more modern approach:
Object.keys(jsonStream.rgDescriptions).forEach(function(key){
  console.log("The " + key + " property has a value of: " +jsonStream.rgDescriptions[key]);
});
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71