如何导出/保存更新的d3.js v4树json数据字符串

时间:2019-03-17 21:45:43

标签: javascript d3.js

我正在使用以下代码:

https://bl.ocks.org/adamfeuer/042bfa0dde0059e2b288

并且正在加载一个非常简单的json字符串来创建树:

{
    "name": "flare",
    "children": [{
        "name": "analytics"
    }, {
        "name": "animate"
    }]
}

所以我想弄清楚的是,在将新的子节点添加到“ flare”节点后(例如),如何创建更新的json字符串以保存新添加的节点?

添加新节点后更新json的示例如下:

{
    "name": "flare",
    "children": [{
        "name": "analytics"
    }, {
        "name": "animate"
    }, {
        "name": "NEW NODE"
    }]
}

是否有一些我找不到的内置函数?还是必须构建自定义功能?如果我需要自定义功能,是否有人可以指出正确的方向呢?非常感谢你!

1 个答案:

答案 0 :(得分:1)

我提出了这种解决方案,它并不完美,值得改进,但是可以起作用, 它将帮助您入门。

下面的所有代码都添加到dndTree.js文件中的更新函数的末尾。

console.log(root); //root contains everything you need
    const getCircularReplacer = (deletePorperties) => { //func that allows a circular json to be stringified
      const seen = new WeakSet();
      return (key, value) => {
        if (typeof value === "object" && value !== null) {
          if(deletePorperties){
            delete value.id; //delete all properties you don't want in your json (not very convenient but a good temporary solution)
            delete value.x0;
            delete value.y0;
            delete value.y;
            delete value.x;
            delete value.depth;
            delete value.size; 
          }
          if (seen.has(value)) {
            return;
          }
          seen.add(value);
        }
        return value;
      };
    };

    var myRoot = JSON.stringify(root, getCircularReplacer(false)); //Stringify a first time to clone the root object (it's allow you to delete properties you don't want to save)
    var myvar= JSON.parse(myRoot);
    myvar= JSON.stringify(myvar, getCircularReplacer(true)); //Stringify a second time to delete the propeties you don't need

    console.log(myvar); //You have your json in myvar

现在您有了json,可以:

  • 下载新的tree.json文件:

     function download(content, fileName, contentType) {
       var a = document.createElement("a");
       var file = new Blob([content], {
         type: contentType
       });
       a.href = URL.createObjectURL(file);
       a.download = fileName;
       a.click();
     }
     download(myvar, 'tree.json', 'text/plain'); 
    
  • 或者您可以直接在文件中写入。

node.js的示例:

    var fs = require('fs');
    fs.writeFile("tree.json", myvar, function(err) {
      if (err) {
        console.log(err);
      }
    });

选中此项以获取更多信息以保存文件:How do I save JSON to local text file