0

For reasons I won't bore you with, ALL elements of my webpage must be embedded into one file.

Between the HTML header tags, I have valid JSON data declared:

<script type="application/json" id="data">
"name": "flare", "children":[{"name": "thing1", ... }]
</script>

Previously this data was written to a JSON file which was referenced by my D3 bar chart scripts as follows:

d3.json("data/file.json", function(root) {
 hierarchy.nodes(root);
 x.domain([0, root.value]).nice();
 down(root, 0);
});

I have been able to pass the embedded JSON to an object after following this thread: Best practice for embedding arbitrary JSON in the DOM?

How can I now successfully pass this object to the D3 bar chart?

Community
  • 1
  • 1

2 Answers2

2

Parsing the embedded JSON object was the hard part, so you've basically got this one figured out. Once you have the embedded JSON parsed and passed to an Object, you can just start using that Object.

Building off of your example, say you had this JSON data embedded in your page:

<script type="application/json" id="data">
    {"name": "flare", "children":[{"name": "thing1", ... }]}
</script>

Then instead of using

d3.json("data/file.json", function(root) {
    ...
}

just extract the body of the function you were using, and load the JSON object at the top:

var root = JSON.parse(document.getElementById('data').innerHTML);
hierarchy.nodes(root);
x.domain([0, root.value]).nice();
down(root, 0);
...
mdml
  • 22,442
  • 8
  • 58
  • 66
0

The method described in the question you've linked to will work. Just call the variable whatever you're using in your D3 code, e.g.

var root = JSON.parse(document.getElementById('data').innerHTML);
Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204