Picking up element in a json array

Asked

Viewed 773 times

0

I need to get the element authorDisplayName of that array json. He’s the return of a requisition ajax. How to take only the element with jquery or javascript?

 "kind": "youtube#commentThread",
 "etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/chdu9X44b3BNrN9QUEyKNGH_eiA\"",
 "id": "z12ts1iicov0ybbex22syzij4tuwyrxyk04",
 "snippet": {
  "channelId": "id",
  "videoId": "id",
  "topLevelComment": {
   "kind": "youtube#comment",
   "etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/gKHFh_4gWxRa4aGZKqb5E1DJnww\"",
   "id": "z12ts1iicov0ybbex22syzij4tuwyrxyk04",
   "snippet": {
    "authorDisplayName": "Nome do autor",
    "authorProfileImageUrl": "imagem",
    "authorChannelUrl": "LINK",
    "authorChannelId": {
     "value": "UCLw8RgF4mQXkA_-ZCXAAyIQ"
    },
    "channelId": "UCIwspRtKNszHhIhl36gREjQ",
    "videoId": "VYw3eYIOJ08",
    "textDisplay": "",
    "textOriginal": "r",
    "canRate": true,
    "viewerRating": "none",
    "likeCount": 0,
    "moderationStatus": "likelySpam",
    "publishedAt": "2016-10-05T19:23:16.000Z",
    "updatedAt": "2016-10-05T19:23:16.000Z"
   }
  },
  "canReply": true,
  "totalReplyCount": 0,
  "isPublic": true
 }
}

My code is like this

$(document).on('click','.enviarComentario', function(){                                         
            var comentario = $('.comentbox').val();
            var id = $(this).attr('videoId');           
            $.ajax({
                    type:'post',            
                    url: 'enviarComentario.php',
                    data : { "comentario" : comentario, "idVideo" : id},
                    success: function (e) {                     
                        alert(e);
                        var res = e;
                        alert(res);
                        var authorDisplayName = res.snippet.channelId;
                        alert(authorDisplayName);
                        var comentarios = $('.comentariosLista').html();        
                        $('.comentariosLista').html("");
                        $('.comentariosLista').html('<div class="media">'+
                                '<div class="media-left">'+
                                    '<a href="#">'+
                                    '<img class="media-object" src="'+res.snippet.topLevelComment.snippet.authorProfileImageUrl+'" alt="...">'+
                                    '</a>'+
                                '</div>'+
                                '<div class="media-body">'+
                                    '<h4 class="media-heading">'+
                                        '<strong>'+e.snippet.topLevelComment.snippet.authorDisplayName+'</strong>'+
                                    '</h4>'+comentario+'</div></div>');                                                                  
                    },
                    error: function(){
                        alert('n deu comentario');
                    }
            }); 
        });
  • Maybe your $.ajax request doesn’t understand that your result is a JSON. You can force this by using 'dataType': 'json' just below the type: post.

  • and don’t forget to use in Google Chrome or Firefox, the tab Network Developer Tools so you can "see" how the request is coming from your server, so there is no PHP error there returning a poorly formed JSON.

  • Apparently your answer is being treated as String. Try to give a var json = JSON.parse(res) var authorDisplayName = json.snippet.channelId;

1 answer

1

The path within the object is snippet > topLevelComment > snippet > authorDisplayName. It doesn’t look like an array, it looks like an object. If this object is inside an array, then you have to iterate the array first and with each iteration you can do as I have below where I called res to the object.

var authorDisplayName = res.snippet.topLevelComment.snippet.authorDisplayName;

var res = {
    "kind": "youtube#commentThread",
    "etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/chdu9X44b3BNrN9QUEyKNGH_eiA\"",
    "id": "z12ts1iicov0ybbex22syzij4tuwyrxyk04",
    "snippet": {
        "channelId": "id",
        "videoId": "id",
        "topLevelComment": {
            "kind": "youtube#comment",
            "etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/gKHFh_4gWxRa4aGZKqb5E1DJnww\"",
            "id": "z12ts1iicov0ybbex22syzij4tuwyrxyk04",
            "snippet": {
                "authorDisplayName": "Nome do autor",
                "authorProfileImageUrl": "imagem",
                "authorChannelUrl": "LINK",
                "authorChannelId": {
                    "value": "UCLw8RgF4mQXkA_-ZCXAAyIQ"
                },
                "channelId": "UCIwspRtKNszHhIhl36gREjQ",
                "videoId": "VYw3eYIOJ08",
                "textDisplay": "",
                "textOriginal": "r",
                "canRate": true,
                "viewerRating": "none",
                "likeCount": 0,
                "moderationStatus": "likelySpam",
                "publishedAt": "2016-10-05T19:23:16.000Z",
                "updatedAt": "2016-10-05T19:23:16.000Z"
            }
        },
        "canReply": true,
        "totalReplyCount": 0,
        "isPublic": true
    }
};
var authorDisplayName = res.snippet.topLevelComment.snippet.authorDisplayName;
alert(authorDisplayName);

  • Vlw, but it didn’t work Aki. If I have to give an Alert this error appears: Typeerror: Cannot read Property 'topLevelComment' of Undefined. Why it will be?

  • @Thiago can put in the question the code jQuery or native Javascritp where you receive the ajax?

  • I added friend

  • @Thiago what gives console.log(typeof e, Array.isArray(e), Object.keys(e)); in the first line of that ajax success?

  • This appeared : String false ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35"36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "47"," "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83"84", "85", "86", "87"88", "89"90", "91", "92"...]

  • @Thiago ok, then and what gives console.log(typeof JSON.parse(e), Array.isArray(JSON.parse(e)), Object.keys(JSON.parse(e)));?

  • Unexpected token < in JSON at position 0

  • @Thiago this looks bad... the ajax returns a badly formatted string and cannot be used as JSON. How are you sending it on the server?

  • What appears on your console, if you do this on the return of Success? console.log(e.snippet.topLevelComment.snippet.authorDisplayName)

  • Try making console.log(JSON.stringify(e, null, ' ')); and see the actual structure of the object being returned.

  • Alert is not recommended to display object structures. Prefer the result in the browser console.

  • @Ivanferrer hi! The questions are for Thiago?

  • Yes @Sergio, for Thiago.

  • @Thiago Ivanferrer wrote to you

Show 9 more comments

Browser other questions tagged

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