简体   繁体   English

Python - 从 JSON 对象列表访问元素

[英]Python - accessing an element from a JSON objects list

I'm new in using python.我是使用 python 的新手。 I've started with some json data, pandas and numpy.我从一些 json 数据、pandas 和 numpy 开始。

I have a list of json objects stored into a txt file.我有一个存储在 txt 文件中的 json 对象列表。 I'm reading the data from the txt file and create a dictionary and then append to my json list each json object from the file.我正在从 txt 文件中读取数据并创建一个字典,然后将 append 到我的 json 列表中,从文件中的每个 json ZA8CFDE6331BD59EB266696

jsonTweetsList = []
with open('tweetsOutput.txt') as f:
    for jsonObj in f:
        tweetDict = json.loads(jsonObj)
        jsonTweetsList.append(tweetDict)

An example of what the file contains:文件包含的示例:

{"created_at":"Sat May 09 12:25:06 +0000 2020","text":"#wbdemotest disliked the taxes and fees","user": {"id":97750949378440806,"id_str":"977509493784408064","name":"Roxana Cepoiu","screen_name":"roxana_cepoiu"}} {"created_at":"Sat May 09 12:25:06 +0000 2020","text":"#wbdemotest 不喜欢税费","user": {"id":97750949378440806,"id_str":"977509493784408064 ","name":"Roxana Cepoiu","screen_name":"roxana_cepoiu"}}

{"created_at":"Sat May 09 12:25:44 +0000 2020","id":1259097218260312065,"id_str":"1259097218260312065","text":"#wbdemotest happy with new services provided","user":{"id":977509493784408064,"id_str":"977509493784408064","name":"Roxana Cepoiu","screen_name":"roxana_cepoiu"}} {"created_at":"2020 年 5 月 9 日星期六 12:25:44 +0000","id":1259097218260312065,"id_str":"1259097218260312065","text":"#wbdemotest 对提供的新服务感到满意","user" :{"id":977509493784408064,"id_str":"977509493784408064","name":"Roxana Cepoiu","screen_name":"roxana_cepoiu"}}

I try to access the name element from the user, but I do not know how.我尝试从用户访问名称元素,但我不知道如何。 Using the below script it does not work for the user-name element, it is working only for created_at and text.使用下面的脚本,它不适用于 user-name 元素,它仅适用于 created_at 和 text。

for tweet in jsonTweetsList:
    print(tweet["created_at"], tweet["text"],tweet["user"][0]["name"])

Can you advise me on how can I access the data from user-name?你能告诉我如何从用户名访问数据吗?

user is not a list, it's just an object, what you need to do is access it directly without the [0] index user不是一个列表,它只是一个 object,你需要做的是直接访问它而不用[0]索引

print(tweet["user"]["name"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM