11

If I have a ajax call:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: function(json_data){
    //What's the efficient way to extract the JSON data and get the value
  }
});

Server returned to my js the following JSON data

{"contact":[{"address":[{"city":"Shanghai","street":"Long
            Hua Street"},{"city":"Shanghai","street":"Dong Quan
            Street"}],"id":"huangyim","name":"Huang Yi Ming"}]}

In my jQuery AJAX success callback function, how to extract the value of "name", value of "address" (which is a list of object) elegantly?

I am not experienced with jQuery and JSON data handling in javascript. So, I would like to ask some suggestions on how to handle this data efficiently. Thanks.

1 Answer 1

12

A JSON string gets parsed into a JavaScript object/array. So you can access the values like you access any object property, array element:

var name = json_data.contact[0].name;
var addresses = json_data.contact[0].address;

Do access the values inside each address, you can iterate over the array:

for(var i = addresses.length; i--;) {
    var address = addresses[i];
    // address.city
    // address.street
    // etc
}

If you have not so much experience with JavaScript, I suggest to read this guide.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.