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.
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.
Your JSON is probably a string. You have to parse it first. Use
var obj = JSON.parse(data);
alert(obj.max_output_watts);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With