Reputation: 3349
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);
}
Upvotes: 0
Views: 1231
Reputation: 340
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>
Upvotes: 2