Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  82] [ 3]  / answers: 1 / hits: 23865  / 11 Years ago, wed, september 11, 2013, 12:00:00

I have a D3 chart where I'm trying to parse an inline JSON formatted array instead of loading the data externally.



Instead of doing something like this:



d3.json(data/tsx.json, function (error, data) {
data.forEach(function (d) {
d.dateOrig = d.date;
d.date = parseDate(d.date);
d.close = +d.close;
});


I just want to parse an inline JSON formatted array like this:



var data = [
{date:1-May-13,close:58.13},
{date:30-Apr-13,close:53.98},
{date:27-Apr-13,close:67.00},
{date:26-Apr-13,close:89.70},
{date:25-Apr-13,close:99.00},
{date:24-Apr-13,close:130.28},
{date:23-Apr-13,close:166.70},
{date:20-Apr-13,close:234.98},
{date:19-Apr-13,close:345.44},
{date:18-Apr-13,close:443.34},
];

data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;


But this doesn't work using the same code I would have used on the first method above.



I've created a Fiddle that sort of works, but I can see that I'm parsing the array wrong and my chart elements are being created multiple times (the same number of times as the length of the array). This does not happen when I load my data externally.



See my comments starting at line 35 in this Fiddle.



http://jsfiddle.net/Critter/Hc7zD/5/



How can I rewrite my code to parse the JSON array properly? I'm stumped! Thanks so much!


More From » json

 Answers
13

It appears to be a typo in your code:



At Line 64 or so, I think you want:



data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
}
);


The change being terminating the forEach right there, instead of the forEach block encapsulating the remainder of the code.



Then, delete the trailing ); at the end of the file, and it looks right to me.


[#75747] Wednesday, September 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
herman

Total Points: 110
Total Questions: 90
Total Answers: 108

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
;