简体   繁体   中英

How to parse a JSON array

new here and hit a roadblock, been searching but can't find the answer with my skill set. Task is pretty simple, I want to parse this http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json which is from a weather station. I have used the W3C tutorial but just can't seem to parse this file, but http://json.parser.online.fr has no problem. All the looping parse examples just give me alert after alert.

All I want is the ability to select temp[0] (out of god knows how many) for example via javascript and have it display on a website. I'm really lost, tried searching and if I've missed the goldmine then my bad. Thanks!

Example code

var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌​43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌​43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';  
var obj = JSON.parse(text); 
document.getElementById("demo").innerHTML = obj.temp[0]; 

First, you need to parse the incoming string as below:

temp_arr = JSON.parse(json_string);

Just loop over the temp_arr array, and in each iteration of loop you'll have one object (tobj). For example, like this:

{"humidity":"40.9000","stationtime":"2014-07-06 21:21:03","temp":"22.6000","timestamp":"2014-07-06T11:20:27.231Z"}

All you have to do is, access it like tobj.temp and use it to display on page.

I have written a jquery implementation at: http://jsfiddle.net/DNH5n/2/

Jquery makes working with JSONP much easier heres an example ( http://jsfiddle.net/icodeforlove/9mBsr/ )

$.getJSON('http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json?callback=?', function (data) {
    data.forEach(function (item) {
        $('body').append(JSON.stringify(item)); 
    });
})

update again

heres another example using your code ( http://jsfiddle.net/icodeforlove/9mBsr/2/ )

var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';

var obj = JSON.parse(text);

document.getElementById("demo").innerHTML = obj[0].temp;

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