Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Edit Json file
#1
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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"}
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  JSON File - extract only the data in a nested array for CSV file shwfgd 2 1,066 Aug-26-2024, 10:14 PM
Last Post: shwfgd
  encrypt data in json file help jacksfrustration 1 2,229 Mar-28-2024, 05:16 PM
Last Post: deanhystad
  parse json field from csv file lebossejames 4 2,018 Nov-14-2023, 11:34 PM
Last Post: snippsat
  Python Script to convert Json to CSV file chvsnarayana 8 4,722 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
  Loop through json file and reset values [SOLVED] AlphaInc 2 5,445 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Converting a json file to a dataframe with rows and columns eyavuz21 13 13,840 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  validate large json file with millions of records in batches herobpv 3 2,184 Dec-10-2022, 10:36 PM
Last Post: bowlofred
  Writing to json file ebolisa 1 1,693 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Trying to parse only 3 key values from json file cubangt 8 6,619 Jul-16-2022, 02:05 PM
Last Post: deanhystad
  Initializing, reading and updating a large JSON file medatib531 0 2,779 Mar-10-2022, 07:58 PM
Last Post: medatib531

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020