简体   繁体   中英

D3/JS mapping a JSON data callback

I have seen many examples with d3.csv() callback mappings such as:

var data = raw_data.map(function(d) { return 
    variable1 : +d.variable1,
    variable2 : +d.variable2
});

However I'm trying to figure out how to use map.() for a JSON callback. The reason being is I have a attribute d: expected number, "MaNn", "NaNz" error. This error if I'm not mistaken, is often associated with data being parsed as a string. The JSON looks to be in numbers/floats, but just in case D3 is parsing my data as strings, I want to map it as numbers so I can rule out the parsed as a string culprit from my console log error. So, what I tried was roughly the same as the csv case above, using the unary + :

var json = raw_json.map(function(d)  { return
    xs: +d.xs,
    ys: +d.ys,
    id: +d.id
});

At this point, the error was still there. However I'm not sure if I fully rejected my null hypothesis of string parse error because I'm not totally confident that my JSON data .map() is of the right syntax. I'm kind of in limbo at the moment.

Question: Is my .map() totally wrong? Is there something more I can do to troubleshoot the expected number error?

I realize that JSON files have a wide range of data structures. Here is a screen shot of what my console.log(raw_json) looks like in the console log:

在此处输入图片说明

Your .map() does not match your JSON data. Your JSON consists of one array having one object containing three arrays for id , xs and ys . To convert all those strings to numerical values you need three separate loops:

var obj = raw_json[0];
obj.id = obj.id.map(id => +id);
obj.xs = obj.xs.map(x => +x);
obj.ys = obj.ys.map(y => +y);

Or, preferably, since you do not need to create new arrays while only converting to numbers, you could also do the conversion on the spot using .forEach() instead of .map() .

const toNum = (d, i, a) => { a[i] = +d };   // Conversion function

var obj = raw_json[0];
obj.id.forEach(toNum);
obj.xs.forEach(toNum);
obj.ys.forEach(toNum);

Have a look at the following working example:

 var raw = ` [{ "id": ["1", "2", "3"], "xs": ["11", "12", "13"], "ys": ["21", "22", "23"] }] `; var data = JSON.parse(raw); const toNum = (d, i, a) => { a[i] = +d }; // Conversion function var obj = data[0]; obj.id.forEach(toNum); obj.xs.forEach(toNum); obj.ys.forEach(toNum); console.dir(data); 

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