D3. Json Function to Return Only Some of Json File Data
I Am Reading Csv File Using D3. Csv Which Works Fine. Reading Csv File Also Renames Columns with a Function: However, I Would Rather Read Same Data from a Json...
I am reading csv file using d3.csv which works fine. Reading csv file also renames columns with a function:
However, I would rather read same data from a json file.
d3.csv("myfile.csv", function(d) {
return {
location: d.identifier,
date: new Date(d.created),
amount: d.count_objects
};
}).then(function getData(rawData) {
console.log(rawData[0]);
});
The console output from d3.csv returns results with renamed columns:
console:
{location: "CO", date: Wed Jan 22 2020 00:00:00 GMT-0500 (Eastern Standard Time), amount: "0"}
I just swapped out csv for json file in same code, expecting it to be read similarly but it isn't.
d3.json("myfile.json", function(d) {
return {
location: d.identifier,
date: new Date(d.created),
amount: d.count_objects
};
}).then(function getData(rawData) {
console.log(rawData[0]);
});
However, the console output from d3.json returns results with orignal json keys:
console:
{created: "2020-01-22T00:00:00.000", identifier: "CO", count_objects: "0"}
What modifications are required for d3.json() to get same results with d3.csv() eg to return results with renamed keys?
1 Answer
d3.json doesn't use a row function, since json data isn't always an array. To processes the data, you can do something like:
d3.json("myfile.json").then(function (json) {
return json.map(function (d) {
return {
location: d.identifier,
date: new Date(d.created),
amount: d.count_objects
};
});
}).then(function getData(rawData) {
console.log(rawData[0]);
});