gpt4 book ai didi

javascript - 将 JSONArray 解析为 Google 折线图

转载 作者:行者123 更新时间:2023-11-28 03:31:21 25 4
gpt4 key购买 nike

我想创建一个动态 Google 折线图,其中填充了 JSONArray 中的数据。我有以下代码:

    <div id="curve_chart" style="margin-bottom: -12px; margin-left: -28px;"></div>

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart0);

function drawChart0() {
var data = new google.visualization.DataTable(JSONArray);
// assumes "day" is a date and "totalfeedings" is a number
data.addColumn('string', 'Day');
data.addColumn('number', 'TotalFeedings');

for (var i = 0; i < JSONArray.length; i++) {
data.addRow([JSONArray[i].Day, JSONArray[i].TotalFeedings]);
}

var options0 = {
curveType: 'function',
legend: 'none',
lineWidth: 6,
width: 440,
height: 180,
backgroundColor: 'transparent',
axisTitlesPosition: 'in',
color: '#286090',
trendlines: {
type: 'linear',
color: 'green',
lineWidth: 3,
opacity: 0.3,
showR2: true,
visibleInLegend: true
},
vAxis: {
gridlines: {
count: 8
}
}
};

var chart0 = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart0.draw(data, options0);
}
</script>

JSONArray 包含以下数据:


{
"data": [
{ "Day": "2019-09-13T00:00:00", "TotalFeedings": 3 },
{ "Day": "2019-09-14T00:00:00", "TotalFeedings": 10 },
{ "Day": "2019-09-15T00:00:00", "TotalFeedings": 14 },
{ "Day": "2019-09-16T00:00:00", "TotalFeedings": 19 },
{ "Day": "2019-09-17T00:00:00", "TotalFeedings": 14 },
{ "Day": "2019-09-18T00:00:00", "TotalFeedings": 24 },
{ "Day": "2019-09-19T00:00:00", "TotalFeedings": 15 },
{ "Day": "2019-09-20T00:00:00", "TotalFeedings": 18 },
{ "Day": "2019-09-21T00:00:00", "TotalFeedings": 14 },
{ "Day": "2019-09-22T00:00:00", "TotalFeedings": 10 },
{ "Day": "2019-09-23T00:00:00", "TotalFeedings": 13 },
{ "Day": "2019-09-24T00:00:00", "TotalFeedings": 9 },
{ "Day": "2019-09-25T00:00:00", "TotalFeedings": 11 },
{ "Day": "2019-09-26T00:00:00", "TotalFeedings": 8 },
{ "Day": "2019-09-27T00:00:00", "TotalFeedings": 7 },
{ "Day": "2019-09-28T00:00:00", "TotalFeedings": 2 }
]
}

图表没有出现。

我想知道我在这里做错了什么。

最佳答案

  1. 创建一个像我下面所做的那样的数组

  2. 您需要执行 JSONArray.data[i].DayJSONArray.data[i].TotalFeedings 才能访问 JSON 数据。

Example here

JSONArray = {
"data": [
{
"Day": "2019-09-13T00:00:00",
"TotalFeedings": 3
},
{
"Day": "2019-09-14T00:00:00",
"TotalFeedings": 10
},
{
"Day": "2019-09-15T00:00:00",
"TotalFeedings": 14
}
//rest of your data
]
}

// change from this
data.addRow([JSONArray[i].Day, JSONArray[i].TotalFeedings]);

// to this
data.addRow([JSONArray.data[i].Day, JSONArray.data[i].TotalFeedings]);

关于javascript - 将 JSONArray 解析为 Google 折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com