我正在尝试解析以下JavaScript对象以填充Highcharts分组图表。我在这里使用python flask框架,但看起来解析这将是最好的,如果我在JavaScript中完成所有操作。不幸的是我是JavaScript的新手,不知道如何正确地解析它。
添加到此我想要获得以下数组
action_count,action_list以及找到传递created_month和year的方法。可能必须将这两件事结合起来,因为它在这个对象中有两个不同的组件。
这是我想要实现的JSFiddle。 jsfiddle.net/4bpjw0uq/6
# JSON Object I am trying to Parse.
{
"api_response": {
"total_counts": [
{
"created_month": 2,
"created_year": 2017,
"action_counts": [
0,
16,
8,
0,
],
"action_list": [
"action 1",
"action 2",
"action 3",
"action 4",
],
"total_monthly_actions": 27
},
{
"created_month": 3,
"created_year": 2017,
"action_counts": [
0,
53,
50,
6,
],
"action_list": [
"action 1",
"action 2",
"action 3",
"action 4"
],
"total_monthly_actions": 154
},
],
"total_installations": 527
}
}
这是highcharts示例
<div class="jumbotron text-center">
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script>
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Actions'
},
xAxis: {
categories: [
'2-17',
'3-17',
'4-17',
],
crosshair: true
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'action 1',
data: [49.9, 71.5, 106.4, 129.2]
}, {
name: 'action 2',
data: [83.6, 78.8, 98.5, 93.4]
}, {
name: 'action 3',
data: [48.9, 38.8, 39.3, 41.4]
}, {
name: 'action 4',
data: [42.4, 33.2, 34.5, 39.7]
}]
});
</script>
</div>
答案 0 :(得分:1)
const api = {
"api_response": {
"total_counts": [
{
"created_month": 2,
"created_year": 2017,
"action_counts": [
0,
16,
8,
0,
],
"action_list": [
"action 1",
"action 2",
"action 3",
"action 4",
],
"total_monthly_actions": 27
},
{
"created_month": 3,
"created_year": 2017,
"action_counts": [
0,
53,
50,
6,
],
"action_list": [
"action 1",
"action 2",
"action 3",
"action 4"
],
"total_monthly_actions": 154
},
],
"total_installations": 527
}
};
const createHighChartData = (apiResponse) => {
let series = [];
const totalCounts = apiResponse.api_response.total_counts;
//console.log(apiResponse.api_response.total_counts);
let temp = []
totalCounts.map((counts) => {
//console.log(counts.action_counts);
const actionCounts = counts.action_counts;
actionCounts.map((action, i) => {
//console.log(action, i);
if (temp[i]){
temp[i].push(action);
} else {
temp.push([action])
}
})
})
//console.log(temp);
temp.map((dp, i) => {
series.push({
name: "Action " + (i + 1),
data: dp
})
})
console.log(series);
return series
}
createHighChartData(api);