Reputation: 5568
I'm using d3.js and I'm having hard time understanding how can I load a JSON which represents a table (columns and rows), which the columns are defined separately.
A normal JSON, which I have no problem loading may look like this:
[
{
"id": 1,
"name": "A green door",
"price": 12.50
},
{
"id": 2,
"name": "A red door",
"price": 12.50
},
{
"id": 3,
"name": "A blue door",
"price": 12.50
}
]
The corresponding JSON with separated columns will look like this:
{
"columns": [
{
"ColumnName":"id",
"DataType":"number"
},
{
"ColumnName":"name",
"DataType":"string"
},
{
"ColumnName":"price",
"DataType":"number"
}
],
"rows": [
[
"1",
"A green door",
"12.50"
],
[
"2",
"A red door",
"12.50"
],
[
"3",
"A blue door",
"12.50"
]
]
}
Is it possible to make d3.js load this kind of JSON without reconstructing a new JSON?
The original structure of the JSON that I receive is not changeable.
Thank you for helping.
Upvotes: 0
Views: 445
Reputation: 14589
There won't be any problem in loading the JSON with separated columns(Format 2) with d3. You will just need to convert the JSON format after loading it, to match the required format of your d3 layout. For that, you may try the code as shown below.
d3.json("path/to/column_json_file_name.json", function(error, data) {
if (error) return console.warn(error);
var columns = data.columns.map(function(d){ return d.ColumnName });
var jsonInRquiredFormat = data.rows.map(function(row,i){
var ob = {};
ob[columns[0]] = parseInt(row[0]);
ob[columns[1]] = row[1];
ob[columns[2]] = parseFloat(row[2]);
return ob;
});
console.log(jsonInRquiredFormat);
});
Output obtained for sample input:
[{
"id": 1,
"name": "A green door",
"price": 12.5
}, {
"id": 2,
"name": "A red door",
"price": 12.5
}, {
"id": 3,
"name": "A blue door",
"price": 12.5
}]
Upvotes: 2