1

so I am trying to parse a JSON response:

{
"success":true,
"rgInventory":{
"7058200129":{
"id":"7058200129",
"classid":"1690096482",
"instanceid":"0",
"amount":"1",
"pos":1
},
"7038515091":{
"id":"7038515091",
"classid":"310776543",
"instanceid":"302028390",
"amount":"1",
"pos":2
},
"6996242662":{
"id":"6996242662",
"classid":"310781169",
"instanceid":"302028390",
"amount":"1",
"pos":3
},

So I need to access the rgInventory to acccess the subsets. The problem is that I try this as my code to parse the JSON:

obj.rgInventory[0]

This normally works for me but it doesn't work this time. The issue is that this is a snippet of the JSON, there are roughly 200 of these responses. How can I parse all of them dynamically?

I only need help getting the data. Thanks!

Tino Caer
  • 443
  • 4
  • 19
  • Why not use [`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)? Also `rgInventory` is an object literal. – Spencer Wieczorek Aug 02 '16 at 22:35
  • If one of the answers below answered your question, the way this site works works, you'd "accept" the answer, more here: ***[What should I do when someone answers my question?](http://stackoverflow.com/help/someone-answers)***. But only if your question really has been answered. If not, consider adding more details to the question. – Blue Aug 03 '16 at 04:49
  • @FrankerZ yea sorry about that, I was going to choose an answer but I had to wait three minutes, I then just forgot about it... – Tino Caer Aug 03 '16 at 13:41

2 Answers2

1

rgInventory is an object, not an array, so it can't be accessed like an array. Notice the { directly after the colon instead of a [?

Use this to get the first element in an object:

var obj = { foo: 'bar' };
console.log(obj[Object.keys(obj)[0]]); //logs 'bar'

Here is a great tutorial on the differences between arrays and objects.

Community
  • 1
  • 1
Blue
  • 22,608
  • 7
  • 62
  • 92
1

First of all, this is not a valid JSON, but anyway you have shared here a JSON object which we can parse it and access sub objects by their keys like this:

var rgInventory = json["rgInventory"];

This is a DEMO snippet:

var json = {
"success":true,
"rgInventory":{
"7058200129":{
"id":"7058200129",
"classid":"1690096482",
"instanceid":"0",
"amount":"1",
"pos":1
},
"7038515091":{
"id":"7038515091",
"classid":"310776543",
"instanceid":"302028390",
"amount":"1",
"pos":2
},
"6996242662":{
"id":"6996242662",
"classid":"310781169",
"instanceid":"302028390",
"amount":"1",
"pos":3
}}};

var rgInventory = json["rgInventory"];
alert(rgInventory[6996242662].id);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • Yea, its weird since I am using the steam api and they say it is JSON, thanks! – Tino Caer Aug 02 '16 at 22:42
  • 1
    You are welcome, and as you can see the sub elements are organized as key/value elements and not as an array so in any case you need to access their values by Key/Name. – cнŝdk Aug 02 '16 at 22:50