CptNemo
CptNemo

Reputation: 6755

Access nested JSON with d3.json()

I have the following JSON

{
    "users":
 {
     "gender":
  {
      "tot":
   [
       {"label":"female", "value":6038},
       {"label":"male", "value":45228},
       {"label":"unknown", "value":32932}
   ]
  }
 }
}

I can load the file with d3.json() and visualise it via console.log() but I can't access the inner values and labels

Please consider the following script

d3.json("../data/m5s/sumStats.json", function(data) {
    console.log(data)
    x.domain(data.map(function(d) {
        return d[0].users[0].gender[0].comment[0].label;
    }));
});

which returns at the third line

Uncaught TypeError: undefined is not a function 

Upvotes: 0

Views: 2367

Answers (1)

amenthes
amenthes

Reputation: 3336

you can access the data in plain object notation:

d3.json("../data/m5s/sumStats.json", function(data) {
    // these are just examples, you don't need them
    console.log(data);
    console.log(data.users);
    console.log(data.users.gender);
    console.log(data.users.gender.tot);

    // this is the important bit: we're not going over 'data' but over a sub-object of data:
    x.domain(data.users.gender.tot.map(function(d) { return d.label; }));
});

Upvotes: 2

Related Questions