Reputation: 35
I Just started writing this script for practice, it will take input and then write it inside Json file. Code looks like this:
import json
command = int(input("Do You Want To Add, Or Remove From List? 1/2 "))
if command == 1:
add_key = input("Type In key Name: ")
add_val1 = input("Type In Value N1: ")
add_val2 = input("Type In Value N2: ")
with open('jjj.json', 'r+') as jjson:
tvsh = json.load(jjson)
new_tvsh = {add_key: [add_val1, add_val2]}
tvsh.update(new_tvsh)
jjson.seek(0)
json.dump(tvsh, jjson)
elif command == 2:
with open('jjj.json', 'r+') as jjson:
tvsh = json.load(jjson)
chooseremove = input("Choose Key To Remove: ")
try:
del tvsh[chooseremove]
except KeyError as ex:
print(f"No such key: {chooseremove} ")
jjson.seek(0)
json.dump(tvsh, jjson)
Json File Looks Like This:
{"Key1":["Val1","Val2"],"Key2":["Val1","Val2"],"Key3":["Val1","Val2"]}
But when i try to remove key(For example key3) my json file will be like this:
{"Key1":["Val1","Val2"],"Key2":["Val1","Val2"]} "Key3":["Val1","Val2"]}
it's taking key outside dict but adding "}" at the end Any Ideas what can i do?
EDIT: Also Tried .pop but same result
Upvotes: 1
Views: 297
Reputation: 463
The error here is that running jjson.seek(0)
followed by json.dump(tvsh, jjson)
does not destroy the contents of the existing file, it only overwrites it. Since the data structure you are writing to the JSON file after remove Key3
is smaller, the entire file is not overwritten (i.e., the "Key3":["Val1","Val2"]}
is left over from your first write).
The solution here is to run jjson.truncate()
after running json.dump(tvsh, jjson)
.
The following program shows the difference, without depending on user input:
#!/usr/bin/env python3
import json
# Test data
initial_data = {
"Key1":["Val1", "Val2"],
"Key2":["Val1", "Val2"],
"Key3":["Val1", "Val2"],
}
final_data = {
"Key1":["Val1", "Val2"],
"Key2":["Val1", "Val2"],
}
with open('testA.json', 'w') as f:
json.dump(initial_data, f)
f.seek(0)
json.dump(final_data, f)
with open('testB.json', 'w') as f:
json.dump(initial_data, f)
f.seek(0)
json.dump(final_data, f)
f.truncate()
Upvotes: 2