There isn't a simple way to data-fy any given json, because not all json objects are the same shape.
By shape, I mean the way that the data is organized. For example, both '{"foo" : 1, "bar" : 2}'
and '{"names" : ["foo", "bar"], "values" : [1, 2]}'
could be used to store the same data, but one stores everything in an object in which the object keys correspond to the names of data points, and one uses separate arrays to store names and values, with corresponding entries having a common array index.
There is, however, a general process you can go through to turn json into data. First, you'll need to parse your json. This can be done with the javascript-standard JSON
object. USe JSON.parse(myJson)
to obtain data from your json object if it's already uploaded to the client. d3.json(my/json/directory, fn(){})
can both load and parse your json, so if you're loading it from elsewhere on your server, this might be a better way to get the json into an object.
Once you have your json packed into a javascript object, you still need to data-fy it, which is the part that will depend on your data. What d3 is going it expect is some form of array: [dataPoint1, dataPoint2, ...]
. For the two examples I gave above, the array you would want would look something like this:
[{'name' : 'foo', 'value' : 1}, {'name' : 'bar', 'value' : 2}]
I've got one element in my array for each data point, with two attributes: value
and name
. (In your example, you would want the attributes letter
and frequency
)
For each of my examples, I would use a different function to create the array. With this line in common:
var rawData = JSON.parse(myJson);
My first json could be packed with this function:
var key;
var data = [];
for(key in rawData){
if(rawData.hasOwnProperty(key)){
data.push({'name' : key, 'value' : rawData[key]});
}
}
For the second example, I would want to loop through each attribute of my object, names
, and values
. My code might look like this:
var i;
var data = [];
for(i = 0; i < rawData.names.length; i++){
data.push({'name' : rawData.names[i], 'value' : rawData.values[i]});
}
Both of these will yield a data-fied version of my original JSON that I can then use in d3.