0

JSON-https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo

I am trying to take the JSON from the above link and place it in the following format(date,open,high,low,close)...

[
[1277424000000,38.58,38.61,37.97,38.10],
[1277683200000,38.13,38.54,37.79,38.33],
[1277769600000,37.73,37.77,36.33,36.60],
[1277856000000,36.67,36.85,35.72,35.93],
]

The date does not need to be Epoch time.

My code....

$.getJSON('https://www.alphavantage.co/query?
function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo', function(data) {
//Get the time series data
var timeseries = data['Time Series (Daily)']
var ohlcarray = [];
//Loop through each time series and convert it to JSON format
  $.each(timeseries, function(key, value) {
        var ohlcdata=[];
        ohlcdata[0]=value[0];//date
        ohlcdata[1]=value[1];//open
        ohlcdata[2]=value[2];//high
        ohlcdata[3]=value[3];//low
        ohlcdata[4]=value[4];//low
        ohlcarray.push(ohlcdata);
  });
console.log(ohlcarray[0]);//test if worked properly
});

The output....

[undefined, undefined, undefined, undefined, undefined]

value[x] returns undefined. Any ideas on why this happens?

Thanks!

Michael
  • 103
  • 1
  • 11

2 Answers2

1

The reason is that in the each loop, the value is not a list but an object. To access it, you'd have to grab it using keys.

ohlcdata[0] = key; //date
ohlcdata[1] = value['1. open']; //open
ohlcdata[2] = value['2. high']; //high
ohlcdata[3] = value['3. low']; //low
ohlcdata[4] = value['4. close']; //low

https://jsfiddle.net/koralarts/7c2fkf93/2/

koralarts
  • 2,062
  • 4
  • 30
  • 48
0

At this point it is already JSON. As Patrick mentioned, getJSON automatically parses json. You will need to access it with the array bracket notation since there are spaces in the property name.

var timeSeries = data['Time Series (Daily)'];

See ex: https://jsfiddle.net/dz0phhn2/6/

dotKn0ck
  • 196
  • 1
  • 1
  • 12