Write JSON parser to format data for pie chart (HighCharts) - javascript

I was fighting with HighCharts quite some hours for formatting the data input to the series option.
Finally I saw the link here solved my problem for data formatting and input.
The data format that would be recognized by HighCharts pie chart is like this (format 1) as indicated by the link above:
[["chrome",15],["firefox",20]]
I actually want dynamic data input from external URL and format the data so that HighCharts can recognized it. The data format I got from the URL is like this (format 2):
[
{
"status": "Stopped \/ Idle",
"val": 17.469444444444,
}, {
"status": "Working",
"val": 0,
}, {
"status": "Headland Turning",
"val": 0,
}, {
"status": "Transport",
"val": 0.15333333333333,
}
]
which is already in JSON format.
I just want to know that is that necessary for me to write a parser for the data from format 2 to format 1? Or Am I missing something that HighCharts can recognize the JSON format data and I don't actually need to write a parser?
I am new to HighCharts so feel free to point that out if some of my problem description does not make sense..Thank you!
EDIT: Thanks for all guys answering my question!

When a script expects data in specific format, you often have to map your data to fit format. This can be modified in server code or using javascript
Can use jQuery $.map to reconfigure an object or array to another array.
DEMO: http://jsfiddle.net/qpsSe/1
Note that trailing commas in sample JSON need removing to validate JSON
/* "json" is your response object, modify variable names to match */
var chartData=$.map( json, function( obj,i){
return [[ obj.status, obj.val]];
})
$.map API Docs
Alternate method in native javascript
var chartData=[];
for( i=0; i<json.length; i++){
chartData.push( [ json[i]['status'], json[i]['val'] ])
}

AFAIK that's just how Highcharts wants its data. That being said, the parser is pretty easy:
var data; // this is your received data
var highchartsData = []; // this is data for highcharts
$.each(data, function(i, e) {
highchartsData.push([e.status, e.val]);
});
One thing to note is that if the data you're receiving is in text (say, a response from an AJAX call) then you need to convert it to a javascript object like so:
var data = $.parseJSON(textData);

You need to make a parser when assigning options as stated in HighCharts preprocessing
Basically, you parse the data and include it in the options:
var serie1 = json.map( function(e) {
return [e.status, e.val];
});
options.series.push({data: serie1});
Here is a working example using $.map and options in Fiddle

Since Highcharts 3.0, categories can also be extracted by giving each point a name and setting axis type to "category".
For a column bar chart this would be:
xAxis: {
type: 'category',
},
series: [{
data: [{
name: 'Point 1',
color: '#00FF00',
y: 1
}, {
name: 'Point 2',
color: '#FF00FF',
y: 5
}]
}]

You can bind chart with JSON data, directly.
You just need to set the json property names as highchart standard.
'Y' for value and 'name' for label.
Your JSON should be as like follow:
[
{
name: "Stopped \/ Idle",
y: 17.469444444444
}, {
name: "Working",
y: 0
}, {
name: "Headland Turning",
y: 0
}, {
name: "Transport",
y: 0.15333333333333
}
]

Related

Server side pagination in KTDatatable (Metronic)

I am new to KTDatatable in Metronic.
I am trying to use server side pagination in Metronic dashboard, and I am parsing the data in a KTDatatable, but I can't find a way to parse the returned data from the API and to view number of pages and each page URL.
The code that I was able to write so far is:
data: {
type: 'remote',
source: {
read: {
url: dataURL,
method: 'GET',
contentType: 'application/json',
map: function(data) {
var cards = data.cards.data;
var currentPage = data.cards.current_page;
var lastPage = data.cards.last_page;
return cards;
}
},
},
pageSize: 10,
serverPaging: true,
},
In this code I was able to get the first ten records but:
1- I wasn't able to parse them the way I want in the table.
2- I wasn't able to show the pages number nor calling the API for the second page or the (x) page I want.
These are the things I want to do.
Thanks in advance.
You can go back to the end of the KT-Datatable documentation to find most of answers you want KT-Datable documentation, but I am gonna explain more hoping it will be more clear.
So the returned value from the API (Json) should look have two main objects meta and data, and it looks something like this:
{
"meta": {
"sort": "desc",
"field": "IssueName",
"page": 1,
"pages": 2,
"perpage": "10",
"total": 11
},
"data": [
{
"IssueName": "******",
"CardNumber": "******"
},
{
"IssueName": "******",
"CardNumber": "******"
}
]
}
And after getting the values of the response from the API you should only return the data object to be parsed by the datatable so the map function should look something like this:
map: function(data) {
return data.data;
}
and it will process the meta data itself.
To parse the data into the columns you should use the same key name of the data in column definition array, so in my example I used it like this:
columns: [
{
field: 'IssueName',
title: columnsTitles.issue,
type: 'string',
},
{
field: 'CardNumber',
title: columnsTitles.card_number,
type: 'string',
},
]
And every time the datatable calls the API it will send more data that will help you give the right response, the data will be on a shape of an array (The field name should be the same as the key):
[
"pagination" => array:4 [
"page" => "1"
"pages" => "2"
"perpage" => "10"
"total" => "11"
],
"sort" => array:2 [
"field" => "IssueName"
"sort" => "desc"
],
]
The sent data is related with the pagination and sorting type you have to get from the API, and you can also add filters and they will be stored in the array in the "query" field, and you can handle them in the backend.

JSON data to valid data array in JS

I need to alter my JSON API from https://demo.piwik.org/?module=API&method=VisitsSummary.getVisits&idSite=7&period=day&date=last3&format=json&token_auth=anonymous
{"2017-12-21":767,"2017-12-22":571,"2017-12-23":31}
to a valid array for my charts in NVD3.js as
[ { "key" : "Page Visits" , "values" : [ [ 1025409600000 , 767] , [ 1028088000000 , 571] , [ 1030766400000 , 31] }]
NOTE: These dates do not match the JSON and Array but highlight the conversion needed, if anyone can explain to me the date format used in NVD3.js that would be great too.
If helpful, I can add the scripts used to get data and display the NVD3 Chart.
You can use array#map to convert your object to array. Then use [ { "key" : "Page Visits" , "values" : result }]; to get the required object.
var data = {"2017-12-21":767,"2017-12-22":571,"2017-12-23":31};
var result = Object.keys(data).map(k => [new Date(k).getTime(), data[k]]);
console.log(result);

Nested JSON Objects with Dimple.js

I'm attempting to create a stacked bar chart with Dimple.JS and D3. However, the JSON file I wish to use with this particular visualization involves nested JSON objects (below). The stacked bar chart I wish to create has the channel category as its x-axis, with the y axis to be the aggregate count of the different locations (with each location as a 'stack'). Here is the original data:
[{
"channel": "politics",
"locations":
[{
"name":"usa",
"count" : 1454
},
{
"name":"mexico",
"count":3543
},
{
"name":"antarctica",
"count":4352
}]
},
{
"channel": "economics",
"locations":
[{
"name":"usa",
"count" : 12431
},
{
"name":"mexico",
"count":314
},
{
"name":"china",
"count":2321
}]
}]
I've flattened the above into the JSON below, but I am having trouble using Dimple's .addSeries() method to create the stack.
[
{
"channel": "politics",
"locations[0].name": "usa",
"locations[0].count": 1454,
"locations[1].name": "mexico",
"locations[1].count": 3543,
"locations[2].name": "antarctica",
"locations[2].count": 4352
},
{
"channel": "economics",
"locations[0].name": "usa",
"locations[0].count": 12431,
"locations[1].name": "mexico",
"locations[1].count": 314,
"locations[2].name": "china",
"locations[2].count": 2321
}
]
My question is this: how can Dimple support either this data encoded in this particular JSON file? Most samples use CSV and TSV files, but I unfortunately have the limit of using only JSON files.
Dimple can't use nested data. You'll have to flatten it on the client side so there's a single JSON object for each intersection of channel/location. Here's an example of how to do that with Underscore.js :
var chartData = _.chain(data)
.map(function(row, index){
// for each original row, return a new row for each location
return _.map(row.locations, function(location){
return {
'channel' : row.channel,
'name' : location.name,
'count' : location.count
};
});
})
.flatten()
.value();
(For every row in the original data set, it will return three rows, one for each location. This will return an array of nested arrays, so it calls flatten to make the whole array 1 level deep.)
Here's a jsBin showing that in action : http://jsbin.com/nuvihu/edit?html,js,output
(output):
If this helps, here is what the data ended up looking like :
[{"channel":"politics","name":"usa","count":1454},{"channel":"politics","name":"mexico","count":3543},{"channel":"politics","name":"antarctica","count":4352},{"channel":"economics","name":"usa","count":12431},{"channel":"economics","name":"mexico","count":314},{"channel":"economics","name":"china","count":2321}]

Javascript FLOT Combined Bar & Line Chart with x-axis as string

I have a bar graph where the x axis is a string, so I need to use a ticks array, I also need to be able to specify the colour of each bar and to also plot a line in the same graph.
The following is the code I have now which has been through many alterations to try and make it work, but I am now stuck.
I cannot get this to display the graph at all, here it is on jsfiddle: http://jsfiddle.net/9x7aJ/4102/
Any help would be appreciated as I have spent the best part of today on trying to solve this.
var fdat = [
{
"color": "#6ECFF6",
"data": [[0,114]]
},
{
"color": "#7BCDC8",
"data": [[1,96]]
},
{
"color": "#FDC68A",
"data": [[2,94]]
}
]
var data = [
{label: "d1", data:fdat, bars: {show: true}},
{label: "d2",data:fdat, lines: {show: true}, points:{show:true}}
];
var opts = {xaxis: {ticks:[[0,"Text 1"], [1,"Text 2"], [2,"Text 3"]]}};
$.plot($("#placeholder"),data,opts);
You cannot have an object with different colors for each data point, data points have to be simple arrays. If you simplify your data to
var fdat = [
[0, 114],
[1, 96],
[2, 94]
]
the graph works (updated fiddle).
If your need different colors for each bar, create one data series for each bar.

Unable to read json data to draw a graph

I am new to jQuery and json. Trying to draw a graph with reference to the demo from
http://www.highcharts.com/stock/demo/
This graph uses data from a json file
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
this file directly started with data. But the json file that I want to use looks something like this
{"name": {
"text1": "on",
"data": {
[1147651200000,67.79],
[1147737600000,64.98],
[1147824000000,65.26],
[1147910400000,63.18],
[1147996800000,64.51],
[1148256000000,63.38],
[1148342400000,63.15],
[1148428800000,63.34],
[1148515200000,64.33],
[1148601600000,63.55],
[1148947200000,61.22],
[1149033600000,59.77],
}
}}
could someone help me with this please
Your json is invalid.
If your data property is an array, so you should use [] to denote the array.
I'm assuming that array is an array of arrays, so inside [], it should have multiple []s.
Like:
[[x1,y1],[x2,y2]...]
Try formatting your code sample as follows...
{
"name": {
"text1": "on",
"data": [
[
1147651200000,
67.79
],
[
1147651200000,
67.79
]
]
}
}
Use something like http://jsonlint.com/ to check your json's validity.

Categories

Resources