0
error while writing to json
I try to write to a empty json file in python. But I got some weird error "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" Here is my code import json def add_to_json(name, price): data = {str(name): str(price)} with open("my_file.json", 'r+', encoding="utf-8") as file: json_file = json.load(file) json_file.update(data) file.seek(0) json.dump(json_file, file) add_to_json("abcd", "efgh") add_to_json("abcd", "efgh")
2 Answers
+ 7
As Lisa already mentioned, there is an issue with the file. I have put some comments in the code and modified it slightly:
import json
def add_to_json(name, price):
data = {str(name): str(price)}
with open("j__.json", 'w', encoding="utf-8") as file: # this CREATES a json file with the content: {'python': 'sololearn'}:
json.dump(data,file) # <--- write json data (dict) to tge json file
with open("j__.json", 'r', encoding="utf-8") as file: # this opens and reads an existing json file:
json_file = json.load(file)
# <--- reading from json file and storing it as dict
json_file.update(data)
# <--- updating dict with new data
file.seek(0)
# <--- set fild pointer to tgd beginning of the file
json_file = json.load(file)
print(f'json_file: {json_file}') # test only
add_to_json("python", "sololearn")
# <--- this will be written to tgd initial file
add_to_json("abcd", "efgh") # <--- this is the data for updating
+ 1
Not sure, but if you want to write to file, maybe it should be "w" or "a" in the with-statement?