Traversing json using Ajax jquery

Asked

Viewed 451 times

1

Guys I have a doubt, how do I go through the Json and recover specific objects through ajax?

Code:

function loadJson(){

$.ajax({
  url: "data.json",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
  $(".done").load("data.json");
});

}

Json:

$.json
[  
   {  
      "name":"Rio de janeiro",
      "contents":[  
         {  
            "moment":"Rio de janeiro",
            "gallery":null,
            "tags":[  
               "Calor",
               "Verão",
               "Sol"
            ],
            "text":"ENxuKBLPgIuaevUGsxahYQwggHiheIBHsYxwiAborXeqJRoacSbdkYeufLSdnSiRzUnuVRuKktmBTDltuJXryfKyxXjDrACJXgIU",
            "contentUrl":null,
            "createdAt":1456231430795,
            "type":"TEXT",
            "socialNetwork":"TWITTER",
            "userName":"MatSproesser",
            "avatarUrl":"https://pbs.twimg.com/profile_images/1207792762/opf_normal.jpg"
         },

2 answers

2


Below is a commented example

$.ajax('data.json').then(function(data) {
    //Converte a string(json) retornada do server para um objeto acessível para o JS
    var meu_json = JSON.parse(data)

    // Printa seu objeto já convertido
    console.log(meu_json);

    // Printa atributo "nome" do seu objeto. Utilize "."(ponto) para acessar os atributos
    console.log(meu_json.nome)

  });

1

When you load a valid JSON via $.ajax the content of your json will be transformed into a javascript object, then all the properties of your JSON will be accessible according to the name of each property, in the code below shows how to access the name and tags:

$(document).ready(function () {

  $.ajax('data.json').then(function(data) {
    console.log(data);
    console.log('name', data.name);
    console.log('tags', data.contents[0].tags);
  });

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.