MrPickle MrPickle - 27 days ago 7x
Javascript Question

Accessing an array inside of JSON object

I have a JSON object formatted like {"Foo": ["B","A","R"]}

I am trying to access the values of the array like this:

var json = "{"Foo": ["B","A","R"]}

expression = JSON.Parse(json, function(key, Value){
if(key == "Foo"){

If I ask for the length of value it returns the correct length of the array, but if I ask for the value it returns undefined and I am not quite sure why.There are other values in the JSON that I am able to access just fine, but they are not arrays. Any insight would be appreciated. Thanks!


You should use JSON.parse like this:

var json = '{"Foo":["B","A","R"]}';
var object = JSON.parse(json);
// object is now and object containing the data from 'json'

var expression = object["Foo"][1]; // object["Foo"] refers to the
                                   // value with key "Foo"

(Calling JSON.parse with a callback parameter is an advanced feature for transforming the JSON object, not reading it. In almost all cases, though, you want to use it like the above code, with no callbacks.)