JSON - https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo
我正在尝试从上面的链接中获取JSON并将其置于以下格式(日期,开放,高,低,关闭)......
[
[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],
]
不 的日期需要为大纪元时间。
我的代码......
$.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
});
输出....
[undefined, undefined, undefined, undefined, undefined]
value [x]返回undefined。关于为什么会发生这种情况的任何想法?
谢谢!
答案 0 :(得分:1)
原因是在each
循环中,value
不是列表而是对象。要访问它,您必须使用密钥来抓取它。
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
答案 1 :(得分:0)
此时它已经是JSON了。正如Patrick所说,getJSON会自动解析json。您需要使用数组括号表示法访问它,因为属性名称中有空格。
var timeSeries = data['Time Series (Daily)'];