简体   繁体   中英

passing data into d3js

I have a json object formatted like so

{
   "tweet":[

     {"text": "hello world"},
     {"text": "hello world"}

   ]
}      

in my code below, when I print out "data" the console tells me I have an Object tweet: Array[131] , but when I print out my "dots" value which I'm binding my data to it says my value is 0: Array[1] . What am I doing wrong?

d3.json("tweets.json", function(error, data){

  if (error) return console.warn(error);

  //tells me I have an `Object tweet: Array[131]`
  console.log(data);
  var dots = svg.selectAll("circle")
      .data(data)
      .enter()
      .append("circle");

  //says I have `0: Array[1]`
  console.log(dots);
}

As comments mention, fix your JSON like provided below. I like to use a JSON validator (like https://jsonformatter.curiousconcept.com/ ) to confirm I have valid JSON data. Also, need to make a few changes in your Javascript. Please see updated Javascript code also below.

JSON file

{
   "tweet":[
      {"text":"hello world"},
      {"text":"hello world"}
   ]
}

Javascript file

d3.json("tweetsTest.json", function (error, data) {

    if (error) return console.warn(error);

    //tells me I have an `Object tweet: Array[131]`
    console.log(data);
    var dots = d3.select("svg")//modified so d3.select("svg") not just svg
        .selectAll("circle")
        .data(data.tweet)//modified, need data.tweet to access because you have root "tweet"
        .enter()
        .append("circle")
        .attr("r", 5)//added r, cx, and cy
        .attr("cx", function (d, i) {
            return (i+1) * 20;
        })//added
        .attr("cy", function (d, i) {
            return 20;
        });//added

    //says I have `0: Array[1]`
    console.log(dots);
});

HTML file

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1,maximum-scale=1"/>
    <script type="text/javascript" src="d3.js"></script>
    <script type="text/javascript" src="d3_stackoverflow34456619.js"></script>
</head>

<body>
    <svg style="width:500px;height:500px;border:1px lightgray solid;"></svg>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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