I'm trying to visualize data retrieved from a JSON file in a REST api. I'm using Morris js to create a simple bar chart. I'm having a hard time figuring out how to properly format the javascript array.
The chart is generated like this:
Morris.Bar({
element: 'myfirstchart',
data: [
{ year: '2008', value: 20 },
{ year: '2009', value: 10 },
{ year: '2010', value: 5 },
{ year: '2011', value: 5 },
{ year: '2012', value: 20 }
],
xkey: 'year',
ykeys: ['value'],
labels: ['Series A']
});
I have been trying to save values from JSON structure in a variable:
var USD = data.d.results[0].ExchangeCross;
var USD2 = data.d.results[0].ApprovedRate;
In order to add them to the chart i tried adding them to an array like this:
var obj = { year: USD, value: USD2 };
And then change data:[] to data:obj. This does not work. The optimal solution would be to run a each function for all the values i need, and then plot them into the chart.
Edit forEach function:
$( document ).ready(function() {
$.ajax({
url: "http://intra.site.com/_vti_bin/ListData.svc/ExchangeRates?$orderby=Modified%20desc",
headers: { 'accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose'},
success: function(data){
var params = {
element: 'myfirstchart',
data: [],
xkey: 'year',
ykeys: ['value'],
labels: ['Series A']
};
var data = JSON.parse(data);
data.d.results.forEach(function(element) {
var obj = { "year": element.ExchangeCross, "value": element.ApprovedRate };
params.data.push(obj);
});
Morris.Bar(params);
}
});
});
You have to load data received as JSON from API into your Morris chart. You do that by looping thru your JSON, creating an object and pushing those into an array.
Assuming that this is the JSON that you receive:
Create a params object to use with your Morris chart, with
dataas an empty array:Parse your JSON (if you have a string):
Iterate through the
resultsarray which is wrapped inside ad, create a compatible object with the values you need and push that object into theparams.dataarray:Call your
Morris.Barwithparams:.