How to load data from an internal JSON array rather than from an external resource / file for a collapsible tree in d3.js?

后端 未结 2 862
孤街浪徒
孤街浪徒 2020-12-14 23:51

I wish to load a JSON data array from within a file to generate a collapsible tree diagram per the Mike Bostock example here. The example uses a correctly formatted external

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-15 00:15

    Thanks for the tips/pointers ... I am a total noob in JS and I fail to understand why full code examples are given rather than snippets. In the python community such answers would usually be punished severely.

    I do have a full example - I hope this allows someone else to avoid the 2 hours of frustration I have just sloughed my way through.

    
    
    
    
    
    
    

    I entered the data as a JSON string - To generate this I used Python

    import json
    with open("flare.json","r") as ifp:
        jd=json.load(ifp)
    
    #JD is a python type of dictionary now
    type(jd)
    
    #I would like a JSON_STRING However
    jstr=json.dumps(jd)
    

    I then extracted the jstr data and put it in a var, which is the line starting var flareStr='{"name": "flare", "children": [{"name":

    The console.log(flareStr) allows me to see what is going on into the web-page - go to your web-browser (firefox is my choice) and look at source...

    Next I parse the string to make it a proper JSON object...

    flare=JSON.parse(flareStr);
    

    And as I am not using the d3.json method, I created my own function (note: I have no idea if a variable is local or global in js... so you may need to clear this up).

    The method to parse the data was taken from the original code -

    function parse_data(flare)
      {
      console.log("in Parse_data")
    
    
      root = flare;
      root.x0 = height / 2;
      root.y0 = 0;
    
          function collapse(d) {
            console.log("in collapse")
            if (d.children) {
              d._children = d.children;
              d._children.forEach(collapse);
              d.children = null;
            }
          }
    
      root.children.forEach(collapse);
      update(root);
      }
    

    which is then simply called via

    parse_data(flare);
    

    I hope this assists someone else.

提交回复
热议问题