2

I've search far and wide, but cannot bind JSON data to a simple scatterplot for the life of me. I've looked at posts and examples, but I can only manage to bind arrays and not JSON. Below, I've tried to simply display JSON data as text and still can't make it work. Please let me know if you have any idea why!

d3_attempt.js

var data;

d3.json("json_data.json",function(error, dataset) {
    if (error) return console.warn(error);

    data = dataset;

    var myscatter = d3.select("#somediv").append("svg")
                    .attr("width", 700)
                    .attr("height", 400);

    myscatter.selectAll("text")
        .data(data.data)
        .enter()
        .append("text")
        .text(function(d){return d)})
});

json_data.json

{
    "data":
    {
        "john": {"name": "john", "age": "13"},
        "matt": {"name": "matt", "age":"14"}
    }
}
4

1 に答える 1

2

うん、配列しかバインドできないので、おそらくデータを配列に変換したいと思うでしょう:

myscatter.selectAll("text")
    .data(d3.values(data.data));

これにより、各textノードに{ name, age }オブジェクトがデータとして提供されます。キーも必要な場合 (この場合は必要ないように見えます)、 を使用できますd3.entries。これにより、 のようなオブジェクトの配列が得られます{ key: "john", value: { name: "John", age: "13" }}

于 2013-08-22T16:59:21.800 に答える