Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get value from json in javascript

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.

like image 662
Darwin Tech Avatar asked Jan 16 '23 02:01

Darwin Tech


2 Answers

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.

like image 182
I Hate Lazy Avatar answered Jan 17 '23 19:01

I Hate Lazy


Your JSON is probably a string. You have to parse it first. Use

var obj = JSON.parse(data);
alert(obj.max_output_watts);
like image 29
Lukas_Skywalker Avatar answered Jan 17 '23 18:01

Lukas_Skywalker