繁体   English   中英

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

[英]How to export/save updated d3.js v4 tree json data string

我正在使用以下代码:

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"
    }]
}

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

我提出的这个解决方案并不完美,值得改进,但有效,它将帮助您入门。

下面的所有代码都添加在 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM