[英]How do I access data correctly in a JSON.parse statement?
I'm trying to work with a JSON array that's been returned via an AJAX call. 我正在尝试使用通过AJAX调用返回的JSON数组。 I'd like to put this data in JQPlot to graph it.
我想将此数据放在JQPlot中以图形方式显示。 When I use hard coded dummy data my graph draws fine.
当我使用硬编码的伪数据时,我的图形绘制良好。 The dummy data looks like this:
虚拟数据如下所示:
var s1 = [200, 600, 700, 1000];
var s2 = [460, -210, 690, 820];
var s3 = [-260, -440, 320, 200];
var ticks = ['May', 'June', 'July', 'August'];
My attempt to use my own data comes from an ajax call into 'garray' and looks like this: 我尝试使用自己的数据来自ajax调用“ garray”,如下所示:
var obj = JSON.stringify(garray);
alert(obj);
/*this displays the following:
{"date":[["2015-05-29","2015-05-12","2015-04-30","2015-03-30","2015-02-27","2015-02-26"]],"close":[[0,3,1,1,0,0]],"high":[[1,3,2,1,0,1]],"low":[[0,-1,0,-1,-1,-1]]} */
obj = JSON.parse(obj);
s1 = obj["date"];
alert(s1);
//the alert above displays: 2015-05-29,2015-05-12,2015-04-30,2015-03-30,2015-02-27,2015-02-26
The problem is that this separation is being interpreted as one variable in JQPlot, as opposed to separate dates. 问题在于,这种分离被解释为JQPlot中的一个变量,而不是分离的日期。 The exact same is happening with the other strings, so I suspect I'm not processing them correctly?
其他字符串也完全一样,所以我怀疑我没有正确处理它们吗? Do I need to use a different approach?
我需要使用其他方法吗?
Each of the fields you have ( date
, close
, etc.) is actually an array of arrays (notice the double [[
and ]]
at the beginning in ending -- an array just needs one of those). 您拥有的每个字段(
date
, close
等)实际上都是一个数组数组(请注意,结尾处的开头是double [[
和]]
-数组只需要其中一个)。 My guess is that the API you're using can return multiple sets of data, and you're just asking for one. 我的猜测是,您使用的API可以返回多组数据,而您只需要一组。
So, you should use obj["date"][0]
(and similarly for the others) 因此,您应该使用
obj["date"][0]
(其他情况类似)
s1 = obj["date"]; // is an array of dates
for( var i = 0; i < s1.length; i++ ){
console.log(s1[i]) // logs each date in the array
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.