如果我使用以下方法从Twitter API解析推文:
tweet.entities.media
我得到了以下的json。但是我如何访问media_url属性?它嵌套在json对象内部的一个非常困难的地方。
tweet.entities.media[0].media_url
返回错误。
{
"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"
}
}
}
]
}
答案 0 :(得分:1)
我如何访问media_url?
在我看来,你只是缺少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>
&#13;
答案 1 :(得分:1)
我想我明白了。 它打破了因为一些推文没有图片.. 我不得不检查空的属性......
return {"image_url":(tweet.entities.media!==undefined)?((tweet.entities.media[0]!=="")?(tweet.entities.media[0].media_url):('')): ('') };