skip to Main Content

If I parse a Tweet from the Twitter API using:

  tweet.entities.media

I get the below json. But how would I access media_url property? Its nested in a really difficult place inside the json object.

 tweet.entities.media[0].media_url

returns an error.

{
  "image": [
    {
      "id": 511403875438301200,
      "id_str": "511403875438301185",
      "indices": [
        44,
        66
      ],
      "media_url": "http://some_url.jpg",
      "media_url_https" : "https: //some_url.jpg",
      "url": "http://whatever.com",
      "display_url": "pic.twitter.com/BNIPh3ZlRD",
      "expanded_url": "https://twitter.com/some_url/1",
      "type": "photo",
      "sizes": {
        "thumb": {
          "w": 150,
          "h": 150,
          "resize": "crop"
        },
        "small": {
          "w": 680,
          "h": 482,
          "resize": "fit"
        },
        "large": {
          "w": 2048,
          "h": 1453,
          "resize": "fit"
        },
        "medium": {
          "w": 1200,
          "h": 851,
          "resize": "fit"
        }
      }
    }
  ]
}

2

Answers


  1. Chosen as BEST ANSWER

    I think I got it. It was breaking because some of the Tweets didn't have images.. I had to check for empty properties...

     return  {"image_url":(tweet.entities.media!==undefined)?((tweet.entities.media[0]!=="")?(tweet.entities.media[0].media_url):('')): ('') };
    

  2. how would I access media_url?

    It appears to me that you are just missing image[0]:

    tweet.entities.media.image[0].media_url
    
    $(document).ready(function() {
    var tweet = jQuery.parseJSON( '{"entities":{"media":{"image":[{"id":511403875438301200,"id_str":"511403875438301185","indices":[44,66],"media_url":"http://pbs.twimg.com/media/BxjfHXxCEAETmig.jpg","media_url_https":"https: //pbs.twimg.com/media/BxjfHXxCEAETmig.jpg","url":"http://whatever.com","display_url":"pic.twitter.com/BNIPh3ZlRD","expanded_url":"https://twitter.com/AWish4Me/status/511403876642463744/photo/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":680,"h":482,"resize":"fit"},"large":{"w":2048,"h":1453,"resize":"fit"},"medium":{"w":1200,"h":851,"resize":"fit"}}}]}}}');
    document.body.innerHTML = tweet.entities.media.image[0].media_url;
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search