Mike
Mike

Reputation: 435

Retrieve JSON from URL

I am trying to retrieve a JSON from a url. So far I have

<script>
var co2;
$(document).ready(function(){
    alert("0");
    $.getJSON(url,function(result){
        var jsonObject = result;
        alert(result);
        alert(result.Cumulative_CO2);
        co2 = result.Cumulative_CO2;
    });
}); 
</script>

the URL returns [{"Cumulative_CO2":"406465.968076","Year":"2013","Month":"3","Day":"29"}]

what I would like to do is take Cumulative_CO2 and store it in a var, but the alert(result) returns [object Object] and alert(result.Cumulative_CO2) returns undefined. Am I doing something wrong retrieving the json? I am brand new to this and cant figure out what to do next.

Upvotes: 0

Views: 155

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

The result is an array of json objects, in this case you need to get the first item in the array and then get the value of property Cumulative_CO2

alert(result[0].Cumulative_CO2);

Also: Need to consider the possibility of the case where the array might return more than one item.

Upvotes: 3

Ben McCormick
Ben McCormick

Reputation: 25718

You want result[0].Cumulative_CO2. The result is wrapped in an array, so access the first item and then get the property from that object.

Upvotes: 2

Related Questions