简体   繁体   中英

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. I'd like to put this data in JQPlot to graph it. 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:

    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. 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). My guess is that the API you're using can return multiple sets of data, and you're just asking for one.

So, you should use obj["date"][0] (and similarly for the others)

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM