简体   繁体   中英

Python - accessing an element from a JSON objects list

I'm new in using python. I've started with some json data, pandas and numpy.

I have a list of json objects stored into a txt file. 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.

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: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"}}

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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