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 this:

 ... $.getJSON(pop_model_dims_url, {model_id: selected}, function(data, jqXHR){ alert(data.max_output_watts); }); ... 

The warning is now just a placeholder, but I don’t understand why the warning value is "undefined". If I do this:

 ... $.getJSON(pop_model_dims_url, {model_id: selected}, function(data, jqXHR){ alert(data); }); ... 

I get a full json dump as expected.

Any help is greatly appreciated.

+4
source share
4 answers

Since your alert(data); gives you a full JSON dump, this probably means that JSON has been encoded twice on the server.

jQuery will parse it once for you, but you will 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 the right decision. The correct solution is to fix it on the server.

Once you do this, you will no longer need $.parseJSON .

+5
source

Your JSON is probably a string. You must take it apart first. Use

 var obj = JSON.parse(data); alert(obj.max_output_watts); 
+3
source

jQuery getJSON must parse the JSON by itself. If JSON comes like this:

 "{ \"max_output_watts\": 150, \"frame_length_inches\": \"62.20\", \"frame_width_inches\": \"31.81\" }" 

The parser mistakenly takes it for a string.

It should look like plain text:

 { "max_output_watts": 150, "frame_length_inches": "62.20", "frame_width_inches": "31.81" } 
+1
source

You need to parse JSON because it does not look like json, as the method is undefined:

Here is the notation using jQuery:

 data = $.parseJSON(data); data.max_output_watts; 

And here's how to get along:

 data = JSON.parse(data); data.max_output_watts; 

Hello!

0
source

Source: https://habr.com/ru/post/1444445/


All Articles