Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a json object using jquery

Tags:

json

jquery

I think that it is a very basic question, but I have spent hours looking for an answer with no luck, I've 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 jquery piece of 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 inside preg.pregunta (message and key values)

Any help?

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

Ok maybe it would be more than obvious or I have to study a bit more; I found that jQuery doesn't parse properly a JSON response if it came along with a HTTP error (400 in this case).

someone knows why this behavior?

I just tested this code in success handler and works perfectly!

$.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 about 2 hours, I've found a straightforward 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 error handler, jQuery returns a complex object describing the error, responseText contains the data retrieved from the server, so, you have to parse it using parseJSON function.

Hope this helps!

like image 754
Manuel Serrano Avatar asked May 26 '12 19:05

Manuel Serrano


1 Answers

Try this:

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

If there were multiple values within the preg.pregunta array, you would need to loop and replace the [0] with your iterating variable.

Also, I don't quite understand why you'd only want to access the reponse in the error handler only?

Finally, the code for accessing the JSON is native javascript. This is because when you receive the response it has been converted into a POJS object, no jQuery required.

like image 71
Rory McCrossan Avatar answered Oct 14 '22 17:10

Rory McCrossan