Skip to content Skip to sidebar Skip to footer

How To Load Json File With Date To Google Charts

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

Solution 1:

the solution you found will work, but does require additional processing on the client.

to pass a real date to google, the json format you found must be used. it is basically the same date string, without the new keyword. you can find the reference here --> dates and times using the date string representation

{
  "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}]},
      ]
}

and yes, the month needs to be reduced by one...

here is an example of the php you could use (not tested)

<?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($arras$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;
?>

then on the client side, you only need to pass the json to the data table constructor.

var data = new google.visualization.DataTable(jsonData);

you don't need to add columns or rows...

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: newDate(2019, 0, 1),
          max: newDate(2019, 11, 31)
        }
      }
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart'));

    chart.draw(data, options);

  });
});

note: async: false on ajax has been deprecated and should no longer be used. use the done callback instead (see above snippet).

Solution 2:

I've just found a solution!!!

Data has to be presented like:

[{"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}]

It is done by getjson.php file:

<?php$fecha = new DateTime();
$strJsonFileContents = file_get_contents("datos_nego2.json");
$arr = json_decode($strJsonFileContents, true);
$result = [];
$i = 0;

foreach($arras$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;?>

Then, in the javascript code:

    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    functiondrawChart() {

      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([
          newDate(array_datos[i].Fecha),
          parseFloat(array_datos[i].Precio),
        ]);
      }

Post a Comment for "How To Load Json File With Date To Google Charts"