How to parse json object using jquery

I think this is a very simple question, but I spent hours searching for an answer without any luck, I have the following json object (generated using play! Framework)

{ "preg.pregunta": [{ "message":"Debes escribir una pregunta", "key":"preg.pregunta", "variables":[] }], "preg":[{ "message": "validation.object", "key":"preg", "variables":[] }] } 

This is my piece of jquery code

 $.ajax({ type: $target.attr('method'), data: dataString, url:$target.attr('action'), dataType: "json", beforeSend: function() { //some stuff }, success:function(response){ //some stuff }, error: function(response){ //I want to use the json response here. } }); 

I want to get all the values ​​inside preg.pregunta ( message and key )

Any help?

UPDATED : well, I don’t have enough reputation to answer myself, this is what I have found so far.

Well, perhaps that would be more than obvious, or I need to learn a little; I found that jQuery does not parse the JSON response properly if it came with an HTTP error (in this case 400).

Does anyone know why this behavior?

I just tested this code in the success handler and it works great!

 $.ajax({ type: $target.attr('method'), data: dataString, url:$target.attr('action'), dataType: "json", beforeSend: function() { }, success:function(response){ //It is working perfectly! $.each(response,function(object){ //first loop of the object $.each(response[object],function(values){ //looping inside arrays console.log(response[object][values].key) //getting value "key" console.log(response[object][values].message) //getting value "message" }); }) }, error: function(response){ //nothing happens here } }); 

UPDATED 2.

after searching for about 2 hours, I found a simple solution:

 error: function(response){ //Note the jQuery.parseJSON function var response = jQuery.parseJSON(response.responseText); $.each(response,function(object){ $.each(response[object],function(values){ console.log(response[object][values].key) console.log(response[object][values].message) }); }) } 

Explanation: when using the error handler, jQuery returns a complex object describing the error, responseText contains data received from the server, so you need to parse it using the parseJSON function.

Hope this helps!

+6
source share
1 answer

Try the following:

 error: function(response) { var pregunta = response["preg.pregunta"][0].message; var key = response["preg.pregunta"][0].key; }, 

If preg.pregunta were several values ​​in the preg.pregunta array, you would need to loop and replace [0] with your iteration variable.

In addition, I do not quite understand why you want to access only the answer in the error handler?

Finally, the code for accessing JSON is native javascript. This is because when you receive the response, it was converted to a POJS object, jQuery is not required.

+2
source

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


All Articles