MrPickle MrPickle - 1 year ago 104
Javascript Question

Accessing an array inside of JSON object from reviver

I have a

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
and I am not quite sure why.There are other values in the
that I am able to access just fine, but they are not arrays. Any insight would be appreciated. Thanks!

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download