MrPickle MrPickle - 2 months ago 18
Javascript Question

Accessing an array inside of JSON object from reviver

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"){
console.log(value[1]);
}
});


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!

Answer

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.)

Comments