我通过PHP的平面JSON输出获得了一个MySQL数据ChartJS图。ChartJS发出以下代码:
function showGraph()
{
{
$.post("data.php?id=0",
function (data)
{
console.log(data);
const date = [];
const time = [];
const temperature = [];
const humidity = [];
//const name = [];
for (var i in data) {
date.push(data[i].date);
time.push(data[i].time);
temperature.push(data[i].temperature);
humidity.push(data[i].humidity);
name.push(data[i].name);
}
PHP脚本提供了平面JSON数据,例如:
{
"timestamp": "1582877101",
"time": "09:05",
"temperature": "18.90",
"humidity": "50.70"
},
{
"timestamp": "1582877161",
"time": "09:06",
"temperature": "18.90",
"humidity": "50.70"
},
由于JSON更改为嵌套数据,因此我的图形不再起作用。新的嵌套JSON看起来像:
[
{
"id": "0",
"name": "Logger 0",
"data": [
{
"date": "2020-02-28",
"time": "09:05",
"temperature": "18.90",
"humidity": "50.70"
},
{
"date": "2020-02-28",
"time": "09:06",
"temperature": "18.90",
"humidity": "50.70"
}
如何再次将嵌套的JSON数据解析为JQUERY变量?
由于data
现在是JSON响应的属性,因此您可以通过ES6 destructuring访问它。请注意,data
现在是一个数组,因此您必须使用forEach,如下所示:
$.post('data.php?id=0', ({name, data}) => {
console.log(data);
const date = [];
const time = [];
const temperature = [];
const humidity = [];
data.forEach(element => {
date.push(element.date);
time.push(element.time);
temperature.push(element.temperature);
humidity.push(element.humidity);
});
});