简体   繁体   中英

Format data for D3

How can I format this sample data for a graph I am making in d3.js?

[
    [
        [
            "2",
            "2013-01-02 00:00:00+00"
        ],
        [
            "3",
            "2012-12-28 00:00:00+00"
        ],
        [
            "3",
            "2012-12-27 00:00:00+00"
        ],
        [
            "1",
            "2012-12-26 00:00:00+00"
        ],
        [
            "1",
            "2012-12-24 00:00:00+00"
        ],
        [
            "4",
            "2012-12-21 00:00:00+00"
        ],
        [
            "1",
            "2012-12-20 00:00:00+00"
        ]
    ],
    [
        [
            "1",
            "2012-12-27 00:00:00+00"
        ],
        [
            "2",
            "2012-12-21 00:00:00+00"
        ],
        [
            "2",
            "2012-12-18 00:00:00+00"
        ],
        [
            "1",
            "2012-12-17 00:00:00+00"
        ],
        [
            "1",
            "2012-11-27 00:00:00+00"
        ],
        [
            "1",
            "2012-11-03 00:00:00+00"
        ],
        [
            "1",
            "2012-10-27 00:00:00+00"
        ]
    ]
]

currently, my javascript console gives me Uncaught TypeError: Cannot use 'in' operator to search for '_dateElement' in NaN within d3.v3.js:1033 when d3 tries to parse this data

it seems that d3 doesn't want to deal with numbers in quotation marks, without quotation marks makes invalid json, which my ajax call will not return, which means I won't be able to parse the arrays in my d3 function.

I believe d3 can parse and format json but I am at an impasse. How do I format this data, the date objects will be my X axis in ascending order, and the Y axis will be a max of the integer values

You will need to parse your input array into an output array with the data in the format you want. As C.Reed says in comments, use parseInt to convert string to number and use d3.time.format to convert string to date. https://github.com/mbostock/d3/wiki/Time-Formatting

var date_in = "2013-01-02 00:00:00+00";
var format = d3.time.format("%Y-%m-%d 00:00:00+00");
var date_out = format.parse(date_in); 

(assumes time is always 0)

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