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() {
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!