Reputation: 18919
Hi I have a simple JSON output:
"{
\"max_output_watts\": 150,
\"frame_length_inches\": \"62.20\",
\"frame_width_inches\": \"31.81\"
}"
which I use in a function like so:
...
$.getJSON(pop_model_dims_url, {model_id: selected}, function(data, jqXHR){
alert(data.max_output_watts);
});
...
The alert is just a placeholder for now, but I don't understand why the alert value is 'undefined'. If I do:
...
$.getJSON(pop_model_dims_url, {model_id: selected}, function(data, jqXHR){
alert(data);
});
...
I get the full json dump as expected.
Any help much appreciated.
Upvotes: 4
Views: 552
Reputation: 4348
jQuery getJSON should parse the JSON by himself. If the JSON comes like that:
"{
\"max_output_watts\": 150,
\"frame_length_inches\": \"62.20\",
\"frame_width_inches\": \"31.81\"
}"
The parser mistaken it for a string.
It should come out as plain text like this:
{
"max_output_watts": 150,
"frame_length_inches": "62.20",
"frame_width_inches": "31.81"
}
Upvotes: 1
Reputation: 4070
You have to parse to JSON, because it looks like not a json, since the method is undefined:
Here is the notation with jQuery:
data = $.parseJSON(data);
data.max_output_watts;
And here is how you should do without:
data = JSON.parse(data);
data.max_output_watts;
Regards!
Upvotes: 0
Reputation: 48761
Since your alert(data);
gives you the full JSON dump, this likely means that the JSON has been double encoded on the server.
jQuery will have parsed it once for you, but you'd need to parse it again.
$.getJSON(pop_model_dims_url, {model_id: selected}, function(data, jqXHR){
data = $.parseJSON(data);
alert(data.max_output_watts);
});
Of course this is not a proper fix. The proper solution is to fix it on the server.
Once you've done that, you won't need $.parseJSON
anymore.
Upvotes: 5
Reputation: 2060
Your JSON is probably a string. You have to parse it first. Use
var obj = JSON.parse(data);
alert(obj.max_output_watts);
Upvotes: 3