Working with JSON and PHP in D3.js

2,530 views
Skip to first unread message

Newbie

unread,
Dec 12, 2012, 8:39:38 PM12/12/12
to d3...@googlegroups.com

Can anyone help? I'm attempting to plot the time on the x-axis of my line graph and having real problems achieving this.

At the moment y-axis depicts "reading":

    d3.json('getdata.php',function (jsondata) { 
    var data = jsondata.map(function(d) { return d.reading; }); 

    var x = d3.scale.linear().domain([0, data.length]).range([0, width]);
    var y = d3.scale.linear().domain([0, d3.max(jsondata, function(d) { 
    return parseInt(d.reading); })]).range([height,0]);

The output from "getdata.php" is in the following format:

[{"reading":"10","Time":"2012-11-01 00:00:00"},{"reading":"10.2","Time":"2012-11-01 00:02:00"}......

I get a parse error if I change:

     var data = jsondata.map(function(d) { return d.reading; }); 

to

     var data = jsondata.map(function(d) { return d.Value; }); 

I know it may seem like a very simple question but how do I read in both "reading" and "Time"?

Would also really appreciate any help with how to format/parse DateTime to depict Time only?

Kai Chang

unread,
Dec 12, 2012, 8:56:24 PM12/12/12
to d3...@googlegroups.com
API Docs on time:

https://github.com/mbostock/d3/wiki/Time

Example using time format and time scale:

http://bl.ocks.org/3883245

Newbie

unread,
Dec 12, 2012, 9:00:47 PM12/12/12
to d3...@googlegroups.com, kai.s...@gmail.com
Thank you - great help.  Still not sure how to deal with the json data - returning reading and time.

Kai Chang

unread,
Dec 12, 2012, 9:10:06 PM12/12/12
to Newbie, d3...@googlegroups.com
That example parses a tsv file into JSON, so it's almost an identical
format to yours except for the time format. These are the lines that
convert the two data fields:

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

Parse data is a function that is defined earlier:

var parseDate = d3.time.format("%d-%b-%y").parse;

You just need to adjust the string in d3.time.format for your unique format.

Kai Chang

unread,
Dec 12, 2012, 9:15:08 PM12/12/12
to Newbie, d3...@googlegroups.com
A pedantic note: The value you've named "jsondata" is not actually
JSON, it's a javascript object (array of objects). I incorrectly
called it JSON in the last email as well.

A javascript object is a superset of JSON, and can include things like
Date objects and functions.
Reply all
Reply to author
Forward
0 new messages