Issue
Complete Python noob here!
I have a json file with all the data I searched using twitter API, I only want to keep certain keys in that file and delete the rest of them but don't know how to do it correctly. so far this is my code and it gave me an error "list indices must be integers or slices, not str"
import json
def read_json(json_file:str)->list:
tweets_data=[]
for tweet in open(json_file, 'r'):
tweets_data.append(json.loads(tweet))
return tweets_data
tags = ["created_at", "full_text"]
tweet_list=read_json('test.json')
for i in tweet_list["tweet"].keys():
if i not in tags:
del tweet_list["tweet"][i]
print (tweet_list[0])
Please send help thanksss!!
Solution
def read_json(json_file:str)->list:
tweets = []
with open(json_file, 'r') as f:
for line in f:
tweets.append(json.loads(line))
return tweets
tags = ['created_at', 'full_text']
tweets = read_json('tweets.json')
for tweet in tweets:
for key in list(tweet.keys()):
if key not in tags:
del tweet[key]
Answered By - Tomward Matthias
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.