Render D3 graph from a string of JSON instead of a JSON file

后端 未结 2 643
自闭症患者
自闭症患者 2020-12-09 10:38

I am trying to render the following Dendrogram from my Rails app: http://bl.ocks.org/mbostock/4063570

I have a model with many attributes, but I would like to manual

2条回答
  •  执笔经年
    2020-12-09 11:14

    First, lets look at what d3.json does.

    d3.json("/assets/flare.json", function(root) {
        // code that uses the object 'root'
    });
    

    This loads the file /assets/flare.json from the server, interprets the contents as JSON and passes the resulting object as the root argument to the anonymous function.

    Where you already have a JSON object, you don't need to use the d3.json function - you can just use the object directly.

    var root = {
       "name": "flare",
       "children": [
         ...
       ]
    };
    // code that uses the object 'root'
    

    If the object is represented as a string, then you can use JSON.parse to get the object:

    var myString = '{"name": "flare","children": [ ... ] }';
    var root = JSON.parse(mystring);
    // code that uses the object 'root'
    

    Second, lets look at what d3.layout.cluster expects of your data. As per the docs:

    ... the default children accessor assumes each input data is an object with a children array ...

    In other words, you data needs to be of the form:

    var mystring = '{
        "name": "Product",
        "children": [
            {
                "name": "id",
                "type": "number",
                "description": "Product identifier",
                "required": true
            },
            ...
            {
                "name": "stock",
                "type": "object",
                "children": [
                    {
                        "name: "warehouse",
                        "type": "number"
                    },
                    {
                        "name": "retail",
                        "type": "number"
                    }
                ]
            }
        ]
    }
    

提交回复
热议问题