无法从d3.js中的json提取图形数据(节点,链接)

时间:2018-06-29 18:29:54

标签: javascript d3.js

经过几天的努力,我终于创建了我的第一个d3.js布局。但是现在我想分离数据和脚本。我试图使用JSON保留数据并从中提取数据。但这没有用。请帮忙。

我尝试了这个,但是随后开始失败:

d3.json("sample.json", function(data) {
  var link = svg.append("g")
            .attr("class", "links")
            .selectAll("line")
            .data(data.links)
            .enter().append("line")
            .attr("stroke-width", function(d) { return Math.sqrt(d.value); });

var node = svg.append("g")
            .attr("class", "nodes")
            .selectAll("circle")
            .data(data.nodes)
            .enter().append("circle")
            .attr("r", 5)
            .attr("fill", function(d) { return color(d.group); })
            .call(d3.drag()
            .on("start", dragstarted)
            .on("drag", dragged)
            .on("end", dragended));
...
)};

这是我正在处理的完整代码。

JSFIDDLE:d3_graph_labelled_edge.js

1 个答案:

答案 0 :(得分:0)

无效的JSON。格式化后(删除最后一行逗号并将单引号替换为双引号):

{
"nodes": [{
        "name": "NE1",
        "full_name": "NE1",
        "type": 2,
        "slug": "12.3",
        "entity": "company",
        "img_hrefD": "",
        "img_hrefL": ""
    },
    {
        "name": "NE2",
        "full_name": "NE2",
        "type": 2,
        "slug": "12.4",
        "entity": "company",
        "img_hrefD": "",
        "img_hrefL": ""
    },
    {
        "name": "NE3",
        "full_name": "NE3",
        "type": 2,
        "slug": "12.3",
        "entity": "company",
        "img_hrefD": "",
        "img_hrefL": ""
    },
    {
        "name": "NE4",
        "full_name": "NE4",
        "type": 2,
        "slug": "12.1",
        "entity": "company",
        "img_hrefD": "",
        "img_hrefL": ""
    },
    {
        "name": "NE5",
        "full_name": "NE5",
        "type": 2,
        "slug": "12.0",
        "entity": "company",
        "img_hrefD": "",
        "img_hrefL": ""
    }
],
"links": [{
        "source": 0,
        "target": 1,
        "value": 1,
        "distance": 15,
        "a": "123",
        "z": "111"
    },
    {
        "source": 0,
        "target": 2,
        "value": 1,
        "distance": 15,
        "a": "123",
        "z": "111"
    },
    {
        "source": 0,
        "target": 3,
        "value": 1,
        "distance": 15,
        "a": "123",
        "z": "111"
    },
    {
        "source": 1,
        "target": 2,
        "value": 1,
        "distance": 15,
        "a": "123",
        "z": "111"
    },
    {
        "source": 1,
        "target": 3,
        "value": 1,
        "distance": 15,
        "a": "123",
        "z": "111"
    },
    {
        "source": 2,
        "target": 3,
        "value": 1,
        "distance": 15,
        "a": "123",
        "z": "111"
    },
    {
        "source": 1,
        "target": 4,
        "value": 1,
        "distance": 15,
        "a": "123",
        "z": "111"
    }
]
}

以下是使用上述JSON的插件:http://plnkr.co/edit/vRrYyjH3mtPz8vEuTZKx?p=preview

推荐:使用JSON Lint进行验证。

希望这会有所帮助。