Search code examples
javascriptparsingjsonp

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]; 

Solution

  • 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;