Python Forum

Full Version: Edit Json file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to add key\value pairs to a Json file. I can write one pair to the file but I can't figure out how to append additional pairs. When I try, it just replaces the current pair. I have tried following this tutorial but I get key errors.
import json 

product_data =  "{}"

product = input("Enter product name. ")
price = input("enter product price. ")
new_product = {product:price} 

load = json.loads(product_data)

load.update(new_product) 

with open("Product.json", "r+") as file:
    json.dump(load, file)
console output:
Output:
Enter product name. milk enter product price. 2.99
File output:
Output:
{"milk": "2.99"}
On line 9, product_data is empty, so load is also empty. I think you probably intend to load in the previously written data here. You'll need to load from the file there, very similarly to how you write to the file later in lines 13 and 14.