user40721 user40721 - 1 year ago 173
Javascript Question

JSON data format in NVD3 chart

I have a chart template for a multi bar chart in NVD3 here:

I have the following JSON data I want to display:

[{"date": 1396828800, "impressions": 49145385},
{"date": 1396915200, "impressions": 46704447},
{"date": 1397001600, "impressions": 47181000},
{"date": 1397088000, "impressions": 47337965},
{"date": 1397174400, "impressions": 51129266},
{"date": 1397260800, "impressions": 60547397},
{"date": 1397347200, "impressions": 62217077},
{"date": 1397433600, "impressions": 49145385},
{"date": 1397520000, "impressions": 46704447},
{"date": 1397606400, "impressions": 47181000},
{"date": 1397692800, "impressions": 47337965},
{"date": 1397779200, "impressions": 51129266},
{"date": 1397865600, "impressions": 60547397},
{"date": 1397952000, "impressions": 62217077}]

I'm looking to use JSON data I have (shown above and also commented out in the fiddle) but don't have any idea how to get it in the format that this NVD3 chart will accept. The chart is currently using sample data that is meaningless to me.

Is there a way to convert my data into something NVD3 will accept? Any help appreciated.

Answer Source

data5 seems to have this format:

  {key: x, values: VALUES, vAxis: 1},
  {key: x, values: VALUES, vAxis: 1} // and maybe more for more colors

and VALUES seems to have this format:

  {x: 0, y: N},
  {x: 1, y: N},
  {x: 2, y: N} // and more for more on the X axis

So you have to rewrite your data to that format. Only it seems you don't have more sources. You have only 1 color. What makes {"date": 1396828800, "impressions": 49145385} one or the other? Is date the X axis?

Assuming the order of your data is correct, and it's only 1 source:

data5 = [{key: 'X', values: [], vAxis: 1}]
yourData.forEach(function(el, i) {
  data5[0].values.push({x: i, y: el.impressions});
     // ^ only 1 source/color
                        // ^ incremental X, starting at 0

You might have to adjust the x and y range somehow. (Maybe vAxis is one?)

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