Dan Dan - 2 months ago 7
JSON Question

How do I access this JSON data using D3?

I am aware that loading JSON in D3 is done like so and this does not produce any errors:

d3.json("sample_data/unique_items.json", function(json) {
// do something
});


Inside this block, I then reference the json file using the
json
variable. Here is the sample structure of the JSON:

{
"unique_items": [
{
"name": "Blah",
"items": [
{"id": 1, "note": "blah"},
{"id": 2, "note": "blah blah"},
{"id": 3, "note": "blah blah blah"}
]
},
{
"name": "Blah2",
"items": [
{"id": 1, "note": "blah"},
{"id": 2, "note": "blah blah"},
{"id": 3, "note": "blah blah blah"}
]
}
]
}


I'm struggling with how to access items in this structure. So for instance I tried this as a test:

for (var item in json["unique_items"]) {
if (json["unique_items"].hasOwnProperty(item)) {
console.log(item["name"]); // 'undefined' error on this line
}
}


I get an undefined error on the line commented as such above. I would expect to see this in the console:

Blah
Blah2


I tried changing that line to
console.log(item.name);
but that produced the same error. I then changed the line to simply
console.log(item);
and the output to the console was
0
. I don't understand this.

So my questions are:


  1. How do I access elements within
    unique_items
    ?

  2. Is there a better way the json should be structured?


Answer

try this

for (var key in json["unique_items"]) {
  var item = json["unique_items"][key];
  if (item) {
    console.log(item["name"]);
  }
}
Comments