user2399453
user2399453

Reputation: 3081

JSON parsing in d3 based on date

I have a JSON file like this below that I want to parse using d3 in a particular way. In the JSON, P1, P2, P3 etc are products and the date within each product is a key and the value is number of quantities of the product sold. I want to be able to filter out for a given month all the days that belong to that month and the quantities of P1, P2, P3 sold for each day. What is the easiest way to do this in d3? I am trying to use d3.json().

 {
    "P1": {
      "2016-06-06": 16,
      "2015-11-19": 20,
      "2015-11-10": 1,
      "2015-11-12": 68,
      "2015-11-15": 27,
      "2015-11-14": 10,
      "2015-11-17": 3,
      "2016-06-27": 39,
       ... //Hundreds of entries like this for various days of the year
     }
     "P2": { ... // Similar to P1}
     "P3": { ... // Similar to P1, P2 }
   }
 }

The output for Oct 2016 should look something like this:

 {
   "2016-10-01": { "P1": 45, "P2": 44, "P3": 12 },
   "2016-10-02": { "P1": 12, "P2": 12, "P3": 12 },
   ...
   "2016-10-31": { "P1": 1, "P2":0, "P3": 4 }
 }

Upvotes: 0

Views: 81

Answers (1)

Mark
Mark

Reputation: 108537

This isn't really a d3 question but rather a simple data transformation in JavaScript:

var json = {
      "P1": {
        "2016-06-06": 16,
        "2015-11-19": 20,
        "2015-11-10": 1,
        "2015-11-14": 10,
        "2015-11-17": 3,
        "2016-06-27": 39
      },
      "P2": {
        "2016-06-06": Math.random() * 10,
        "2015-11-12": Math.random() * 10,
        "2015-11-15": Math.random() * 10,
        "2015-11-14": Math.random() * 10,
        "2015-11-17": Math.random() * 10,
        "2016-06-27": Math.random() * 10
      },
      "P3": {
        "2016-06-06": Math.random() * 10,
        "2015-11-19": Math.random() * 10,
        "2015-11-10": Math.random() * 10,
        "2015-11-12": Math.random() * 10,
        "2015-11-15": Math.random() * 10,
        "2015-11-14": Math.random() * 10
      }
    };
    
    var output = {};
    for (p in json){
      var v = json[p];
      for (d in v){
        if (!output[d]){
          output[d] = {};
        }
        output[d][p] = v[d];
      }
    }
    console.log(output);

Upvotes: 1

Related Questions