How should I loop/parse specific values from json object with lots of nested arrays?

- 1 answer

Ad

I need to manipulate the data in this JSON file.

I need to create two arrays. One with everything from the date column, and one with everything from the close column.

In other words, from each of the nested arrays in the data object, I need to pull out all the values at position [0] to create a new array then do the same for all values at position [4].

I saved down the JSON file to my server using:

file_put_contents("VIX.json", fopen("https://www.quandl.com/api/v3/datasets/YAHOO/INDEX_VIX.json?api_key=xxxx", 'r'));

What is the best approach for doing this? PHP or Javascript? Ultimately the two arrays will be used to create a Chart.js.

My initial thoughts are something like:

date = new Array();
var i, data;
for (i = 0; i < dataset.data.length; i++)
{
  date.push(dataset.data[i].something[0]);
}

None of the nested arrays have names which is currently confusing me. This is what im googling at the moment. Used something as a placeholder in these notes. Any pointers appreciated.

Ad

Answer

Ad

in Javascript

var date = [];
var list = json.dataset.data;
for(i in list)
   date.push(list[i][0]);

in PHP

You can try this

decoding json to be able to fetch the object in php to browse a php object, the used operator is -> once you reach the true array of position's set, read it by foreach

<?php

$o = file_get_contents("VIX.json");
$o = json_decode($o);

$date = [];
$list = $o->dataset->data;
foreach($list as $set)
{
    $date[] = $set[0];
    //printf("x: %f, y: %f, z: %f\n", $pos[1], $pos[2], $pos[3]);
}
Ad
source: stackoverflow.com
Ad