【发布时间】:2021-09-17 07:37:02
【问题描述】:
我有一个多级/复杂的 json 文件 - twitter.json,我只想从这个 json 文件中提取作者 ID。
这就是我的文件“twitter.json”的外观:
[
[
{
"tweets_results": [
{
"meta": {
"result_count": 0
}
}
],
"youtube_link": "www.youtube.com/channel/UCl4GlGXR0ED6AUJU1kRhRzQ"
}
],
[
{
"tweets_results": [
{
"data": [
{
"author_id": "125959599",
"created_at": "2021-06-12T15:16:40.000Z",
"id": "1403732993269649410",
"in_reply_to_user_id": "125959599",
"lang": "pt",
"public_metrics": {
"like_count": 0,
"quote_count": 0,
"reply_count": 1,
"retweet_count": 0
},
"source": "Twitter for Android",
"text": "⌨️ Canais do YouTube:\n\n1 - Alexandre Garcia: Canal de Brasília"
},
{
"author_id": "521827796",
"created_at": "2021-06-07T20:23:08.000Z",
"id": "1401998177943834626",
"in_reply_to_user_id": "623794755",
"lang": "und",
"public_metrics": {
"like_count": 0,
"quote_count": 0,
"reply_count": 0,
"retweet_count": 0
},
"source": "TweetDeck",
"text": "@thelittlecouto"
}
],
"meta": {
"newest_id": "1426546114115870722",
"oldest_id": "1367808835403063298",
"result_count": 7
}
}
],
"youtube_link": "www.youtube.com/channel/UCm0yTweyAa0PwEIp0l3N_gA"
}
]
]
我已经阅读了许多类似的 SO 问题(包括但不限于):
- Access the key of a multilevel JSON file in python
- Multilevel JSON Dictionary - can't extract key into new dictionary
- How to extract a single value from JSON response?
- how to get fields and values from a specific key of json file in python
- How to select specific key/value of an object in json via python
- Python: Getting all values of a specific key from json
但是这些 json 的结构非常简单,当我尝试复制它时,我遇到了错误。
根据我的阅读,contents.tweets_results.data.author_id 是参考的方式。我正在使用contents = json.load(open("twitter.json")) 加载。任何帮助表示赞赏。
编辑:@sammywemmy 和 @balderman 的代码都对我有用。我接受了@sammywemmy,因为我使用了那个代码,但我想以某种方式归功于他们。
【问题讨论】:
标签: python json dictionary