Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading json file to d3.js

I've used the force.js of d3 for visualization purpose.

Following is the snippet of full js:

d3.json("test.json", function(json) {
  force.nodes(json.nodes)
      .links(json.links)
      .start();
});

The test.json file is currently in same location as that of the js file. It works fine. The files are within the 'pages' folder of my web-application. If I use the http url "http://localhost:8084/FMS/faces/pages/test.json" in place of "test.json" it works fine. But if I use "/Users/subashbasnet/test.json" i.e. the path of the file in place of "test.json" it doesnot work.

If I set json output to var and use in place of "test.json" it doesnot work. Eg:

 var myjson = "{"nodes":[{"name":"MYriel","group":1},{"name":"Labarre","group":2}],"links":[{"source":1,"target":0,"value":1}]}";
    d3.json(myjson, function(json) {
      force.nodes(json.nodes)
          .links(json.links)
          .start();
    });  

My .jsp file has following output:

<html>
<head></head>
<body>
<pre>{"nodes":[{"name":"MYriel","group":1},{"name":"Labarre","group":2}],"links":[{"source":1,"target":0,"value":1}]}</pre>
</body>
</html>

How am I suppose to load the json within the <pre> tag in place of "test.json" .

Solution to either of the problem is very much awaited. Thanks in advance.

like image 512
Subash Basnet Avatar asked Apr 28 '26 15:04

Subash Basnet


1 Answers

If you're generating the data in your JSP then you could simply have it do

<script>var theData = (<%= unquotedJsonData %>);</script>

which produces a JS object directly rather than a JSON string

<script>var theData = ({"nodes":[...]});</script>

Then you don't need to use d3's json parser, just do

force.nodes(theData.nodes)....
like image 67
Ian Roberts Avatar answered May 01 '26 06:05

Ian Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!