简体   繁体   English

JSON输出文件格式

[英]JSON Output File Format

I am using Canvasjs Charts to do my graphing from PHP / MySQL. 我正在使用Canvasjs图表从PHP / MySQL进行绘图。 Everything works as expected except for the creating of my JSON file. 除了创建JSON文件外,一切都按预期进行。

Canvasjs requires the JSON file to look as follow: Canvasjs要求JSON文件如下所示:

callback({  
   "dps":
[{"division":"Xaxis VALUE","units":Yaxis VALUE}]
})

However, when creating my JSON file it is 但是,在创建我的JSON文件时

[{"division":"Xaxis VALUE","units":Yaxis VALUE}]

All I want to know is how do I add the opening tag and closing tag in the sjon file from my script. 我只想知道如何在脚本中的sjon文件中添加开始标记和结束标记。

Here is the last part of my code that creates the JSON file: 这是创建JSON文件的代码的最后一部分:

$output_data= array();
    while($row = mysqli_fetch_array($result))
    {
        $output_data[] = array(
                                'division' => $row["division"],     
                                'units' => $row["units"]

                                );
    }

return json_encode($output_data, JSON_NUMERIC_CHECK);    
echo json_encode($output_data, JSON_NUMERIC_CHECK);   
}




$file_name = 'myresult2'.'.json';

if(file_put_contents($file_name, get_data()))
{
    echo $file_name. 'file created';
}
else
{
  echo 'Error';  
}

?>

Additional Data: This is the code that generates the graph. 其他数据:这是生成图形的代码。

<script>

var chart = null;
var dataPoints = [];

window.onload = function() {



chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    theme: "light",
    title: {
        text: "Graph Header"
    },
    axisY: {
        title: "% Verified",
        titleFontSize: 12,
        labelFontSize: 12,
        valueFormatString: "#.##%"      

    },
    axisX: {
        title: "Division",
        titleFontSize: 12,
        labelFontSize: 12
    },    
    data: [{
        type: "column",
        yValueFormatString: "#.##%",
        dataPoints: dataPoints
    }]
});


$.getJSON("myresult.json?callback=?", callback);    

}

function callback(data) {   
    for (var i = 0; i < data.dps.length; i++) {
        dataPoints.push({
            label: data.dps[i].division,
            y: data.dps[i].units
        });
    }
    chart.render(); 
}

</script>

Please try 请试试

// change this
$output_data[] = array(

// to this
$output_data['dps'][] = array(

What you need to do is enclose you created array in a new array with a key named dps . 您需要做的是使用名为dps的项将创建的数组封装在一个新数组中。

So after your while loop you should do something like this 因此,在您的while循环之后while您应该执行以下操作

$json_data['dps']=$output_data;

return json_encode($json_data, JSON_NUMERIC_CHECK);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM