James
James

Reputation: 1485

Iterate over array with $.each

I have the following JSON structure and I'm trying to grab the 'title' value

{
    "ok": true,
    "messages": [{
        "type": "message",
        "subtype": "file_share",
        "file": {
            "name": "Football_and_Hurling_Images.txt",
            "title": "Football and Hurling Images"
        }
    }]
}

Upvotes: 1

Views: 32

Answers (2)

Ankit Kathiriya
Ankit Kathiriya

Reputation: 1231

this code will work for you.

 YourJSON.messages[0].file.title;

Upvotes: 0

Sandeep Nayak
Sandeep Nayak

Reputation: 4757

You can Iterate like this, in case of multiple messages:

  var obj = {
    "ok": true,
    "messages": [{
      "type": "message",
      "subtype": "file_share",
      "file": {
        "name": "Football_and_Hurling_Images.txt",
        "title": "Football and Hurling Images"
      }
    }, {
      "type": "message2",
      "subtype": "file_share",
      "file": {
        "name": "Football_and_Hurling_Images.txt",
        "title": "Football and Hurling Images2"
      }
    }, {
      "type": "message3",
      "subtype": "file_share",
      "file": {
        "name": "Football_and_Hurling_Images.txt",
        "title": "Football and Hurling Images3"
      }
    }]
  }
  $.each(obj.messages, function(index, msg) {
    //console.log(msg);
    console.log(msg.file.title);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Upvotes: 1

Related Questions