JSON data to valid data array in JS - javascript

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);

Related

Extract json data contains list in values using Node JS

I want to extract the data based on keys,
Ex: I want order values, How to get it in node js
const json = {"order": {
"PRD_SHIRT_048": [
"price",
"productId",
"quantity"
],
"PRD_TOP_047": [
"price",
"productId",
"quantity"
]
}};
I'm not sure what exactly is your question, but if you want to access nested properties, you can do it like this:
json.order.PRD_SHIRT_048
This will return:
[
"price",
"productId",
"quantity"
]
And if you want to get all the keys of order object, you can use Object.keys(json.order)
This will return
["PRD_SHIRT_048", "PRD_TOP_047"]

extracting particular values from JSON

I am using Google Distance Matrix API and the response I got was in JSON:
{
"destination_addresses" : [ "Chandigarh, India" ],
"origin_addresses" : [ "Delhi, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "244 km",
"value" : 243506
},
"duration" : {
"text" : "3 hours 54 mins",
"value" : 14069
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I want to get the following values from JSON, destination_address, origin_address, distance, duration, and status. This is my code that I am trying out:
import requests as r
import json
a = r.get("https://maps.googleapis.com/maps/api/distancematrix/json?origins=Delhi&destinations=Chandigarh&key=key")
#text form of a
tfa = a.text
print(tfa)
with open('data.json','w') as outfile:
json.dump(tfa,outfile)
json_data = json.loads(tfa)
print(json_data["destination_addresses"])
print(json_data["origin_addresses"])
print(json_data["rows"][0]["elements"][0]["distance"])
print(json_data["rows"]["elements"]["duration"])
The output that I am receiving gives me destination origin and distance, but I get an error when I try to grab duration, also the values inside the distance are printed as 'text':'244km','value':23432, but I only want to get the values not their labels. Is there any way to do that? Also is it possible to limit the values extracted inside the distance element (because I only want the text not the value)?
print(json_data["rows"][0]["elements"][0]["distance"]["value"])
Adding ["value"] to your current code will only show the value.
print(json_data["rows"]["elements"]["duration"])
You try to get something from the same level as the distance but you forget the [0] in this line. You can basically copy and paste the code that prints the distance value but replace distance by duration:
print(json_data["rows"][0]["elements"][0]["duration"]["value"])

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}]

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.

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

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
}
]

Categories

Resources