【发布时间】:2020-09-20 06:08:56
【问题描述】:
我是解析 json 文件的新手,尽管尝试了几个小时,但我还是找不到访问 json 对象中我想要的值的方法。这是我的代码:
# Access a tweet id and get the tweet info, then save to a txt file
tweet_id = df_tae['tweet_id'][0]
tweet = api.get_status(tweet_id, tweet_mode='extended')
with open('tweet_json_test.txt', "a") as outfile:
json.dump(tweet._json, outfile)
# Later on, open the file and try to extract the 'media_url' address
with open('tweet_json_test.txt') as json_file:
image = json.load(json_file)
我在帖子底部复制了“图片”的摘录
然后当我打电话时:
image['id']
我得到:892420643555336193,这很棒:-)
但是当我打电话时:
image['media']
我收到以下错误
KeyError Traceback (most recent call last)
<ipython-input-849-665e447555a9> in <module>
----> 1 image['media']
KeyError: 'media'
如何访问 media_url 字符串?我已经尝试了我能找到和想到的一切,经过几个小时的捣乱。我知道我可以使用 tweepy API 来获取它,但希望以后能够从 json.txt 中提取它。
# The image file looks like this (extract only for brevity):
{'created_at': 'Tue Aug 01 16:23:56 +0000 2017',
'id': 892420643555336193,
'id_str': '892420643555336193',
'full_text': "This is Phineas. He's a mystical boy. Only ever appears in the hole of a donut. 13/10",
'truncated': False,
'display_text_range': [0, 85],
'entities': {'hashtags': [],
'symbols': [],
'user_mentions': [],
'urls': [],
'media': [{'id': 892420639486877696,
'id_str': '892420639486877696',
'indices': [86, 109],
'media_url': 'http://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
'media_url_https': 'https://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
'url': 'https......',
'display_url': '.....',
'expanded_url': 'https://twitter.com/dog_rates/status/892420643555336193/photo/1',
'type': 'photo',
'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'},
'medium': {'w': 540, 'h': 528, 'resize': 'fit'},
'small': {'w': 540, 'h': 528, 'resize': 'fit'},
'large': {'w': 540, 'h': 528, 'resize': 'fit'}}}]},
【问题讨论】:
-
“我已经尝试了我能找到和想到的所有东西,经过几个小时的折腾。”当您有一个无法弄清楚的
KeyError时,您应该尝试的第一件事是检查.keys()实际上是什么。您可以做的另一件事是在特定于 JSON 的查看器中查看您的 JSON 文件(任何现代 Web 浏览器都应该提供),以便查看它的结构。
标签: python json parsing twitter tweepy