Reputation: 85
The .json file I want to update has this structure:
{
"username": "abc",
"statistics": [
{
"followers": 1234,
"date": "2018-02-06 02:00:00",
"num_of_posts": 123,
"following": 123
}
]
}
and I want it to insert a new statistic like so
{
"username": "abc",
"statistics": [
{
"followers": 1234,
"date": "2018-02-06 02:00:00",
"num_of_posts": 123,
"following": 123
},
{
"followers": 2345,
"date": "2018-02-06 02:10:00",
"num_of_posts": 234,
"following": 234
}
]
}
When working with
with open(filepath, 'w') as fp:
json.dump(information, fp, indent=2)
the file will always be overwritten. But I want the items in statistics to be added. I tried reading the file in many possible ways and append it afterwards but it never worked.
The data is coming written in the information variable just like
information = {
"username": username,
"statistics": [
{
"date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"num_of_posts": num_of_posts,
"followers": followers,
"following": following
}
]
}
So how do I update the .json file that my information is added correctly?
Upvotes: 4
Views: 17953
Reputation: 1
You could use this function:
def append_statistics(filepath, num_of_posts, followers, following):
new_statistics_record={
"date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"num_of_posts": num_of_posts,
"followers": followers,
"following": following
}
with open(filepath, 'r') as fp:
information = json.load(fp)
information["statistics"].append(new_statistics_record)
with open(filepath, 'w') as fp:
json.dump(information, fp, indent=2)
Upvotes: 0
Reputation: 1061
You need to read the .json
file and then append the new dataset and dump that data. See the code.
import json
appending_statistics_data = {}
appending_statistics_data["followers"] = 2346
appending_statistics_data["date"] = "2018-02-06 02:10:00"
appending_statistics_data["num_of_posts"] = 234
appending_statistics_data["following"] = 234
with open(file.json, 'r') as fp:
data = json.load(fp)
data['statistics'].append(appending_statistics_data)
#print(json.dumps(data,indent=4))
with open(file.json, 'w') as fp:
json.dump(data, fp, indent=2)
Upvotes: 0
Reputation: 1649
You would want to do something along the lines of:
def append_statistics(filepath, num_of_posts, followers, following):
with open(filepath, 'r') as fp:
information = json.load(fp)
information["statistics"].append({
"date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"num_of_posts": num_of_posts,
"followers": followers,
"following": following
})
with open(filepath, 'w') as fp:
json.dump(information, fp, indent=2)
Upvotes: 7
Reputation: 737
Normally, you don't directly update the file that you are reading from.
You might consider:
Upvotes: -1