0

I am using a get request from a server API and I am making a request and then doing this:

var resp = JSON.parse(response);

I call to the server providing 0001 & 0002 as arguments and after the JSON.parse it returns an array such as:

{"0001":{"id":1},"0002":{"id":2}}

I know that traditionally if i were given static responses such as

{"placeID":{"id":1},"placeID":{"id":2}}

I could do this:

resp.placeId.id

but given that the return names aren't always the same how can I access that first value resp.0001.id given that 0001 may not always be the value returned?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
user3916570
  • 780
  • 1
  • 9
  • 23

2 Answers2

1

Use a for...in loop.

for(var property in resp) {
    console.log(property + ": " + resp[property]);
}
Dave
  • 10,748
  • 3
  • 43
  • 54
0

You can access the "0001" element of the response like this: resp["0001"].id Since you say that you're providing the id in the query, you presumably have it stored in a variable somewhere.

If you really want to access the first element in the response, you can't use JSON.parse, because you'll lose the ordering information once you suck that data into an object. And if you have to care about the order of the elements, then that JSON is badly-formed, and should be using an array instead of a top-level object.

Mark Bessey
  • 19,598
  • 4
  • 47
  • 69