Search code examples
javascriptjqueryinstagraminstagram-apiinstagram-graph-api

Instagram post's caption is not showing properly


I am trying to get instagram profile's post with captions, everything is working fine except captions. It showing : [object Object]

I haven't used any api.

My code:

function nFormatter(num){
    if(num >= 1000000000){
      return (num/1000000000).toFixed(1).replace(/\.0$/,'') + 'G';
    }
    if(num >= 1000000){
      return (num/1000000).toFixed(1).replace(/\.0$/,'') + 'M';
    }
    if(num >= 1000){
      return (num/1000).toFixed(1).replace(/\.0$/,'') + 'K';
    }
    return num;
  }
  $.ajax({
    url:"https://www.instagram.com/bhudiptaakash?__a=1",
    type:'get',
    success:function(response){
      $(".profile-pic").attr('src',response.graphql.user.profile_pic_url);
      posts = response.graphql.user.edge_owner_to_timeline_media.edges;
      posts_html = '';
      for(var i=0;i<posts.length;i++){
        caption = posts[i].node.edge_media_to_caption;
        likes = posts[i].node.edge_liked_by.count;
        posts_html += '<a href="https://instagram.com/p/'+shortcode+'">: '+caption+';
      }
      $(".posts").html(posts_html);
    }
  });

How can I solve this??


Solution

  • The value of the edge_media_to_caption property is an object like this:

    {
        "edges": [{
            "node": {
                "text": "Still alive"
            }
        }]
    }
    

    You need to loop over the edges and get the node.text properties.

    for (var i = 0; i < posts.length; i++) {
      let caption = posts[i].node.edge_media_to_caption.edges.map(e => e.node.text).join('<br>');
      let likes = posts[i].node.edge_liked_by.count;
      posts_html += '<a href="https://instagram.com/p/' + shortcode + '">: ' + caption + '</a>';
    }