Note that there are some explanatory texts on larger screens.

plurals
  1. PORender D3 graph from a string of JSON instead of a JSON file
    text
    copied!<p>I am trying to render the following Dendrogram from my Rails app: <a href="http://bl.ocks.org/mbostock/4063570" rel="nofollow noreferrer">http://bl.ocks.org/mbostock/4063570</a></p> <p>I have a model with many attributes, but I would like to manually nest those attributes and simply use string interpolation to build up my own JSON string, then pass that to d3 directly.</p> <p>Here is my code:</p> <pre><code> &lt;%= javascript_tag do %&gt; var width = 960, height = 2200; var cluster = d3.layout.cluster() .size([height, width - 160]); var diagonal = d3.svg.diagonal() .projection(function(d) { return [d.y, d.x]; }); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(40,0)"); **d3.json("/assets/flare.json", function(root) {** var nodes = cluster.nodes(root), links = cluster.links(nodes); var link = svg.selectAll(".link") .data(links) .enter().append("path") .attr("class", "link") .attr("d", diagonal); var node = svg.selectAll(".node") .data(nodes) .enter().append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }) node.append("circle") .attr("r", 4.5); node.append("text") .attr("dx", function(d) { return d.children ? -8 : 8; }) .attr("dy", 3) .style("text-anchor", function(d) { return d.children ? "end" : "start"; }) .text(function(d) { return d.name; }); }); d3.select(self.frameElement).style("height", height + "px"); &lt;% end %&gt; </code></pre> <p>Here is my (unminified) JSON string:</p> <pre><code>var mystring = '{ "name": "Product", "properties": { "id": { "type": "number", "description": "Product identifier", "required": true }, "name": { "type": "string", "description": "Name of the product", "required": true }, "price": { "type": "number", "minimum": 0, "required": true }, "tags": { "type": "array", "items": { "type": "string" } }, "stock": { "type": "object", "properties": { "warehouse": { "type": "number" }, "retail": { "type": "number" } } } } }'; </code></pre> <p>Things I've tried:</p> <ol> <li><p>minifying the JSON so it's inputted as just one line (no effect)</p></li> <li><p>running JSON.parse(mystring) on the string</p></li> <li><p>looking through the D3 documentation and and googling for a way to modify the following function to accept a string instead of a file path:</p> <pre><code>d3.json("/assets/flare.json", function(root) { var nodes = cluster.nodes(root), links = cluster.links(nodes); </code></pre></li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload