[英]How to load JSON file with date to Google Charts
由於 json 格式數據未正確擬合,我無法使用谷歌圖表 plot 數據。 我無法弄清楚如何操縱數據以獲得預期的格式。 數據來自 csv 文件。
我從 php 應用了file_get_contents()
,並返回:
[{"Fecha3":1566259200000,"Precio":30.0},
{"Fecha3":1566345600000,"Precio":6.0},
{"Fecha3":1566432000000,"Precio":4.0},
{"Fecha3":1566518400000,"Precio":44.0},
{"Fecha3":1566777600000,"Precio":80.0},
{"Fecha3":1566864000000,"Precio":2.0}
]
(簡稱說明)
所以我將 Unix 日期轉換為谷歌圖表需要的格式。
當我應用下面的 php 代碼時, getjson.php文件中的 output 是:
{"new Date(2019, 08, 20)":30,
"new Date(2019, 08, 21)":6,
"new Date(2019, 08, 22)":4,
"new Date(2019, 08, 23)":44,
"new Date(2019, 08, 26)":80,
"new Date(2019, 08, 27)":2
}
(簡稱說明)
getjson.php
<?php
$fecha = new DateTime();
$strJsonFileContents = file_get_contents("datos_nego2.json");
$arr = json_decode($strJsonFileContents, true);
$result = [];
$i = 0;
// Loop to convert the unix date and sort the data
foreach($arr as $item) {
$uses1 = $item['Fecha3']/1000;
$uses2 = $item['Precio'];
$fecha->setTimestamp($uses1);
$datevar = "new Date(" .$fecha->format('Y, m, d') . ")";
// I think months have to be months - 1
$result[$datevar] = $uses2;
$i++;
}
$jsonTable = json_encode($result);
echo $jsonTable;
?>
然后,我加載的文件是javascript里面的代碼:
var jsonData = $.ajax({
url: "getjson.php",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
data.addColumn('date', 'Fecha');
data.addColumn('number', 'Number');
var options = {
[...]
hAxis: { // I put fixed dates for testing
viewWindow: {
min: new Date(2019, 0, 1),
max: new Date(2019, 11, 31)
},
[...]
顯示了圖表,但沒有顯示數據。 Javascript console.log(jsonData) 顯示:
我在這里讀到的格式應該是:
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
但我不知道如何在這種方式轉變!
我嘗試過但失敗的可能解決方案:
如上所述將 csv 原始文件轉換為 json 樣式。
在var jsonData
下面添加 javascript 代碼來操作它。
我在其他示例中看到了不同的解決方案:
data.addRows([
[new Date(2019, 1, 1), 0.2], [new Date(2019, 2, 1), 0.8],
[new Date(2019, 3, 1), 0.4], [new Date(2019, 4, 1), 0.4],
]);
我也嘗試過,但我從未達到 plot 數據。
我將不勝感激任何建議或代碼片段。
非常感謝您的時間和考慮::-)
您找到的解決方案將起作用,但確實需要在客戶端上進行額外處理。
要將真實日期傳遞給 google,必須使用您找到的 json 格式。
它基本上是相同的日期字符串,沒有new
關鍵字。
您可以在此處找到參考 --> 使用日期字符串表示的日期和時間
{
"cols": [
{"label":"Date","type":"date"},
{"label":"Charge","type":"number"}
],
"rows": [
{"c":[{"v":"Date(2019, 7, 20)"},{"v":20}]},
{"c":[{"v":"Date(2019, 7, 21)"},{"v":21}]},
{"c":[{"v":"Date(2019, 7, 22)"},{"v":22}]},
]
}
是的,月份需要減少一...
這是您可以使用的 php 示例(未經測試)
<?php
$fecha = new DateTime();
$strJsonFileContents = file_get_contents("datos_nego2.json");
$arr = json_decode($strJsonFileContents, true);
// create data table, with columns
$table = [];
$table['cols'] = [
['label' => 'Date', 'type' => 'date'],
['label' => 'Charge', 'type' => 'number']
];
// Loop to convert the unix date and sort the data
$rows = [];
foreach($arr as $item) {
$uses1 = $item['Fecha3']/1000;
$uses2 = $item['Precio'];
$fecha->setTimestamp($uses1);
// month does have to be - 1
$datevar = "Date(".$fecha->format('Y').", ".((int) $fecha->format('m') - 1).", ".$fecha->format('d').")";
// create rows
$result = [];
$result[] = ['v' => (string) $datevar];
$result[] = ['v' => (float) $uses2];
$rows[] = ['c' => $result];
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
然后在客戶端,您只需將 json 傳遞給數據表構造函數。
var data = new google.visualization.DataTable(jsonData);
您不需要添加列或行...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
$.ajax({
url: 'getjson2.php',
dataType: 'json'
}).done(function (jsonData) {
var data = new google.visualization.DataTable(jsonData);
var options = {
hAxis: {
viewWindow: {
min: new Date(2019, 0, 1),
max: new Date(2019, 11, 31)
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, options);
});
});
注意: ajax 上的async: false
已被棄用,不應再使用。
改用done
回調(參見上面的代碼段)。
我剛剛找到了解決辦法!!!
數據必須呈現如下:
[{"Fecha":"2019, 08, 20","Precio":30},{"Fecha":"2019, 08, 21","Precio":6},{"Fecha":"2019, 08 , 22","Precio":4},{"Fecha":"2019, 08, 23","Precio":44},{"Fecha":"2019, 08, 26","Precio":80} ,{"Fecha":"2019, 08, 27","Precio":2},{"Fecha":"2019, 09, 09","Precio":48},{"Fecha":"2019, 09 , 10","Precio":2}]
它由getjson.php文件完成:
<?php
$fecha = new DateTime();
$strJsonFileContents = file_get_contents("datos_nego2.json");
$arr = json_decode($strJsonFileContents, true);
$result = [];
$i = 0;
foreach($arr as $item) { //foreach element in $arr
$uses1 = $item['Fecha3']/1000; //etc
$uses2 = $item['Precio'];
$fecha->setTimestamp($uses1);
$datevar = $fecha->format('Y, m, d');
$result[$i]['Fecha'] = $datevar;
$result[$i]['Precio'] = $uses2;
$i++;
}
$jsonTable = json_encode($result);
echo $jsonTable;
//echo $strJsonFileContents;
?>
然后,在 javascript 代碼中:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getjson2.php",
dataType: "json",
async: false
}).responseText;
var array_datos = JSON.parse(jsonData)
var longitud_array = array_datos.length;
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Charge');
for (var i = 0; i < longitud_array; i++) {
console.log(array_datos[i]);
data.addRow([
new Date(array_datos[i].Fecha),
parseFloat(array_datos[i].Precio),
]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.