0

I have a piece of code using getJSON to grab the data. The response looks like this:

[["SSP II",3],["Limitations",2],["Disputes",2],["PSS",4],["Debit Card",5]]

I am trying to loop through the response and build a simple table.

$.each(json, function(key, value) {
        alert(key + ' ' + value);
    });

I tried the above code but it alerts 0 [object Object].

How can I get the values from this response?

SBB
  • 8,560
  • 30
  • 108
  • 223

1 Answers1

0

[object Object] means that you try to parse an object directly to a string (your alert()).

But if you want to see the actual values like {name="SSP II"} you need to parse the json to a string like this:

alert(key+ ' ', JSON.stringify(value));

if you want to access the values of each array you could do this:

alert(value['name']);//alerts the first string ("SSP II")
Nano
  • 1,398
  • 6
  • 20
  • 32
  • `yntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data alert(key+ ' ', JSON.parse(value));` – SBB Jun 06 '14 at 16:47
  • `value` is not JSON, so you can't parse it as JSON. – Felix Kling Jun 06 '14 at 16:48
  • sry i meant JSON.stringify :P – Nano Jun 06 '14 at 16:49
  • Doesn't really explain how to access the values though. – Felix Kling Jun 06 '14 at 16:50
  • the alert is blank :/ – SBB Jun 06 '14 at 16:54
  • what does `console.log(json);` show you? – Nano Jun 06 '14 at 16:55
  • @SBB: I believe the actual data is different from what you posted. As suggested in the duplicate answer, do `console.log` data first and inspect its structure. Then identify which information you want to access and use loops and property access accordingly. – Felix Kling Jun 06 '14 at 16:55
  • console.log(json)returns `[Object { name="SSP II", y=3, visible=true}, Object { name="Limitations", y=2, visible=true}, Object { name="Disputes", y=2, visible=true}, Object { name="PSS", y=4, visible=true}, Object { name="Debit Card", y=5, visible=true}]` – SBB Jun 06 '14 at 16:57
  • then you need `value['name']` and not `value[0]` for example – Nano Jun 06 '14 at 16:59
  • That seemed to work - `alert(value['y'] + ' ' + value['name']);` - Will `Y` always be used as the value? – SBB Jun 06 '14 at 17:01
  • if you have a variable amount of keys, you could also use another loop. But yes, `value['y']` will always return the value in `[{y=""}]` – Nano Jun 06 '14 at 17:03