【问题标题】:Parse nested json data to JQUERY variables used in ChartJS将嵌套的 json 数据解析为 ChartJS 中使用的 JQUERY 变量
【发布时间】:2020-02-28 15:38:46
【问题描述】:

我通过 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 变量?

【问题讨论】:

    标签: javascript jquery arrays json


    【解决方案1】:

    由于 data 现在是您的 JSON 响应的一个属性,您可以通过 ES6 destructuring 访问它。注意data现在是一个数组,因此你必须使用forEach,像这样:

    $.post('data.php?id=0', ({ name, data }) => {
        console.log(name, 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);
        });
    });
    

    【讨论】:

    • 谢谢,但是发布您的代码会创建一个完整的空白屏幕,而不是没有数据的图表。我认为第 1 步是让代码再次工作,第 2 步是升级到 ES6。
    【解决方案2】:

    答案如下:

    $.getJSON("data.php?id=<?php printf($id)?>",
    function (data)
    {
        const date = [];
        const time = [];
        const temperature = [];
        const humidity = [];
        const name = data[0].name;
    
        data[0].data.forEach(element => {
            date.push(element.date);
            time.push(element.time);
            temperature.push(element.temperature);
            humidity.push(element.humidity);
        })
    

    所以我已将 data[0]. 添加到循环中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多