0

I am not able to parse the JSON string in D3.js if I keep it. If I mention any JSON file name I am able to display the graph.

CODE
    d3.json("mperday.json",function(json){
        //graph displayed now
});
var myjson = "[
[
    {
        "time": "2014-02-19",
        "y": 10
    }
],
[
    {
        "time": "2014-02-19",
        "y": 12
    }
],
[
    {
        "time": "2014-02-19",
        "y": 14
    }
]]";




d3.json(myjson,function(json){
        //graph not displaying now
});



d3.json(JSON.parse(myjson),function(json){
        //graph not displayed now
});

Kindly, provide me some solution.

Karthik
  • 470
  • 8
  • 25
  • 2
    If `var myjson = [` is the code you are trying to parse, it is not a string so parsing it is useless and an error. Hence why the last one will not work. **Any error messages in the console**? – epascarello Apr 11 '15 at 13:29
  • 1
    You should not call `d3.json` but instead use the `myjson` in your rendering logic. – Daniel B Apr 11 '15 at 13:31
  • @epascarello : No no error messages in console – Karthik Apr 11 '15 at 13:38

1 Answers1

0

It's unclear why you have both JSON text and a call to a function that makes an ajax request for JSON, but here's how you might want to set up your code:

var myjson = "[
  [{"time": "2014-02-19", "y": 10}],
  [{"time": "2014-02-19", "y": 12}],
  [{"time": "2014-02-19", "y": 14}]
]";

var getData = function(cb) {
  if (myjson) {
    if (typeof myjson == "string") {
      myjson = JSON.parse(myjson);
    }
    cb(myjson);
  } else {
    d3.json("mperday.json", function(data) {
      myjson = data;
      cb(myjson);
    });
  }
}

getData( function(json) {
   //graph
});
Wex
  • 15,539
  • 10
  • 64
  • 107