I can't plot data with google charts because of json format data is not properly fitted. I can't figure out how manipulate the data for get the expected format. The data come from a csv file.
I applied file_get_contents()
from php, and returns:
[{"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}
]
(shorted for explanation)
So I convert Unix date to the format that Google Charts needs.
When I applied the php code below, the output from getjson.php file is:
{"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
}
(shorted for explanation)
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;
?>
Then, I load the file is inside the javascript code:
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)
},
[...]
Graph is shown but data isn't.
Javascript console.log(jsonData) shows:
I've read here that format should be:
{
"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}]}
]
}
But I don't know how to transform on that way!
Possible solutions I tried but I failed:
Convert csv original file to a json style as mentioned above.
Add javascript code below
var jsonData
to manipulate it.
I've seen in others examples, different solutions:
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],
]);
I also tried but I never achieve to plot data.
I would appreciate any advice or snippet code.
Really thanks for time and consideration! :-)