0

I have the following JSON file below:

{"myArea":[{
 "name": "ny 01",
 "data": [63]
}]}

I use the code below to retrieve the data:

 $(document).ready(function () {   
  $.getJSON('area.json',function(area){
    console.log(area[0][0]);
  });   
});

However the data is not being retrieved. Console log says [object object] or undefined name when trying console.log(area[0]) or console.log(area[0].name). What is the proper way to access the data?

Claude
  • 417
  • 1
  • 8
  • 15

3 Answers3

2

Your root JSON object is an 'object'! You can access properties by using area['name'] or area.name (where name is a valid key).

In your case, you have a key called myArea: area['myArea'].

The result of this expression will be the following array (expressed in JSON here):

[{
 "name": "ny 01",
 "data": [63]
}]

Now, you can grab the first element from the myArea array by using area['myAray'][0]. This will result in the following object being returned:

{
 "name": "ny 01",
 "data": [63]
}

Accessing the data is rather easy now (but pay attention to data, it is an array!)

$(document).ready(function () {   
  $.getJSON('area.json',function(area){
    console.log(area['myArea'][0]['name']);    "ny 01"
    console.log(area['myArea'][0]['data'][0]); 63
  });   
});
ComFreek
  • 29,044
  • 18
  • 104
  • 156
0

In your posted code, area has one property named myArea.

console.log(area.myArea) would give you:

[{"name": "ny 01", "data": [63]}]

console.log(area.myArea[0] would give you:

{"name": "ny 01", "data": [63]}

To access data of the first element:

console.log(area.myArea[0].data[0]

would give you 63

dc5
  • 12,341
  • 2
  • 35
  • 47
0

You are treating "area" like an array (by trying to access the item with index zero) but it is an object. Instead try accessing the "myArea" attribute of the object.

var area = {"myArea":[{
  "name": "ny 01",
  "data": [63]
}]};

area[0]; // => undefined, because there is no attribute with key "0".
area['myArea']; // => [{name:"ny 01",...}], same as "area.myArea".
maerics
  • 151,642
  • 46
  • 269
  • 291