d3 js - loading json without a http get

JavascriptJsond3.jsBubble Chart

Javascript Problem Overview


I am learning d3. There are certain ways of loading the data in d3 js. But all of them seem to make a HTTP GET. In my scenario, I already have the json data in a string. How can I use this string instead of making another http request? I tried to look for documentation for this but found none.

This works:

d3.json("/path/flare.json", function(json) {
    //rendering logic here
}

Now, if I have:

//assume this json comes from a server (on SAME DOMAIN)
var myjson = '{"name": "flare","children": [{"name": "analytics","children": [{"name": "cluster","children": [{"name": "MergeEdge", "size": 10 }]}]}]}'; 

How do I use already computed 'myjson' in d3 & avoid a async call to server? Thanks.

Javascript Solutions


Solution 1 - Javascript

Simply replace d3.json call with

json = JSON.parse( myjson );

IE:

var myjson = '{"name": "flare","children": [{"name": "analytics","children": [{"name": "cluster","children": [{"name": "MergeEdge", "size": 10 }]}]}]}';

// d3.json("/path/flare.json", function(json) { #delete this line

    json = JSON.parse( myjson ); //add this line

    //rendering logic here

//} #delete this line

UPDATE 09/2013

Original code has changed. So varname json should be root:

// d3.json("flare.json", function(error, root) { #delete this line

    root = JSON.parse( myjson ); //add this line

    //rendering logic here

//} #delete this line

Solution 2 - Javascript

The answer from chumkiu worked great for me but needed a couple of tweaks - in the latest version of the d3 bubble chart, you need to define root rather than json, as in

 root = JSON.parse( myjson );

Alternatively, you could replace "root" with "json" in the rest of the code of course. :-)

For anyone coming to this answer with questions about d3 node-link trees that utilize local data sets, this answer worked great for me - many thanks to the contributors on this page.

Solution 3 - Javascript

According to this example:

http://phrogz.net/JS/d3-playground/#StockPrice_HTML

Here they are storing the graph data within the variable $data, and setting it via the .data($data) function.

I'd apply this method to whatever graph you are using.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRaviView Question on Stackoverflow
Solution 1 - JavascriptLuca RainoneView Answer on Stackoverflow
Solution 2 - JavascriptJohn SharpView Answer on Stackoverflow
Solution 3 - JavascriptdardoView Answer on Stackoverflow