D3/JS mapping a JSON data callback

故事扮演 提交于 2019-12-25 09:26:09

问题


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:


回答1:


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);


来源:https://stackoverflow.com/questions/43911190/d3-js-mapping-a-json-data-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!