tibi
tibi

Reputation: 186

python json.decoder.JSONDecodeError while writing to a json

I try to write to a empty json file in python like this.

def add_to_json(name, price):
    data = {str(name): str(price)}
    with open("produse.json", 'r+', encoding="utf-8") as file:
        json_file = json.load(file)
        json_file.update(data)
        file.seek(0)
        json.dump(json_file, file)

I got some weird error message when I run the code : json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). I think maybe is from json.load()?

Upvotes: 1

Views: 1638

Answers (1)

Maurice Meyer
Maurice Meyer

Reputation: 18106

You just need to check if the file is empty:

import json


def add_to_json(name, price):
    newObject = {str(name): str(price)}
    with open("produse.json", 'r+', encoding="utf-8") as file:
        data = file.read().strip()  # Just to be safe: Remove all whitespaces.
        json_file = json.loads(
            data or '{}'
        )  # data evaluates to None if empty. If None use a empty JSON string!
        json_file.update(newObject)
        file.seek(0)
        json.dump(json_file, file)


add_to_json('foo', '2.0')
# Verify:
print(open("produse.json", 'r').read())

Out:

{"foo": "1.0"}

Upvotes: 4

Related Questions