javascript - 使用生成的 json 对象代替 d3.json

标签 javascript jquery json d3.js

我错过了很多时间来解决这个问题,但很不幸。我知道如何使用外部文件渲染 d3 树,但如何使用生成的对象渲染 d3 树。我通过这段代码获取 Json 对象:

   $.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
        .then(function (a, b) {
            return $.extend(a[0], b[0]);
        })
        .then(function (data) {
           var json = JSON.stringify(data);
            console.log('['+ json +']');

并将 json 添加到 d3.json

treeJSON = d3.json(json, function (error, treeData) {

所以整个代码看起来像:

function load() {

    $.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
        .then(function (a, b) {
            return $.extend(a[0], b[0]);
        })
        .then(function (data) {
           var json = JSON.stringify(data);
            console.log('['+ json +']');

// Get JSON data
    treeJSON = d3.json(json, function (error, treeData) {

最有趣的部分是控制台日志自定义,例如正确的字符串:

[{"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]}]

但我仍然收到错误:

GET http://localhost:63342/testMerg/%7B%22text%22:%22Alas%22,%22icon%22:%22…SH%22%7D]%7D,%7B%22text%22:%22CDISC%22%7D,%7B%22text%22:%22BRIDG%22%7D]%7D 404 (Not Found)

我尝试使用我在此处找到的一些示例中的字符串方法:

      .then(function (data) {
           var json = JSON.stringify(data);

// Get JSON data
    treeData = JSON.parse( data );

但出现错误

Uncaught SyntaxError: Unexpected token o

所以我放弃了...有人可以帮助我吗?

最佳答案

出现问题是因为 data 是一个对象,并且您尝试解析该对象。但是 JSON.parse 函数需要一个字符串作为参数。

您可以直接分配treeData = data。 (不需要解析)。

否则您应该尝试对对象进行字符串化,然后解析字符串化的 json。

var json = JSON.stringify(data);
treeData = JSON.parse(json);

var data = {"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]};

//treeData = data;

json = JSON.stringify(data);

console.log(JSON.parse(json));

关于javascript - 使用生成的 json 对象代替 d3.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35738506/

相关文章:

jquery - jCarousel Lite - 水平和垂直居中图像

json - 是否为 null 有效 JSON(4 字节,仅此而已)

javascript - react : TypeError: Cannot read property 'Item' of undefined

javascript - Fancytree 以编程方式触发加载

javascript - 使用javascript获取最高id

arrays - 快速解码单个对象与对象数组的 JSON

javascript - 使用 session.Storage 传递包含 Array 的 JSON 对象

javascript - 我可以为单个平台添加 meteor 包吗

javascript - 使用 Vanilla JavaScript 进行分页

javascript - 按双重嵌套值对 JSON 数组进行排序?