D3 意外值转换,不接受变量

D3 unexpected value translate, won't accept variable

本文关键字:不接受 变量 转换 意外 D3      更新时间:2023-09-26

我有一个奇怪的错误,D3 不会获取变量引用的 JSON 数据,但如果我通过控制台日志将其打印出来并将其复制粘贴到同一变量中,D3 会获取它。

所以这个 JSON 源不起作用:

function reformat(data) {
var jsonObject = JSON.parse(data, function(k, v) {
    return (typeof v === "object" || isNaN(v)) ? v : parseInt(v, 10);
});
var treeData = (JSON.stringify(makeTree(jsonObject), null, 4));
//etc code for D3 
}

但是,如果我从字面上通过控制台打印它,并声明如下:

treeData = [
    {
        "id": 1,
        "name": "Start",
        "children": [
            {
                "id": 2,
                "name": "Decision A",
                "children": [
                    {
                        "id": 4,
                        "name": "Possibility A-1",
                        "children": [
                            {
                                "id": 8,
                                "name": "Consequence A-1"
                            }
                        ]
                    },
                    {
                        "id": 5,
                        "name": "Possibility A-2",
                        "children": [
                            {
                                "id": 9,
                                "name": "Consequence A-2"
                            }
                        ]
                    }
                ]
            },
            {
                "id": 3,
                "name": "Decision B",
                "children": [
                    {
                        "id": 6,
                        "name": "Possibility B-1",
                        "children": [
                            {
                                "id": 10,
                                "name": "Consequence B-1"
                            }
                        ]
                    },
                    {
                        "id": 7,
                        "name": "Possibility B-2",
                        "children": [
                            {
                                "id": 11,
                                "name": "Consequence B-2"
                            }
                        ]
                    }
                ]
            }
        ]
    }
];

突然工作正常。我无法继续复制和重新声明变量。如果输出相同,为什么不接受它?

该函数在加载网页时被调用一次:

 function reqListener () {
      console.log(this.responseText);
    }
    var oReq = new XMLHttpRequest(); 
    oReq.onload = function() {
       reformat(this.responseText);
    };
    oReq.open("get", "getData.php", true);
    oReq.send();

为什么要串化 JSON 并将其传递给 treeData?

而不是

var treeData = (JSON.stringify(makeTree(jsonObject), null, 4));

这样做

var treeData = makeTree(jsonObject);

这应该有效。