Click here to Skip to main content
15,666,479 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi have a requirement to insert new values when needed in JSON file.
I used to get the new data and need to insert existing json file. If "Honda", "toyota" doesn't exists, need to create and insert new values. If exists need to add new values under respective fields.

sample json file:
	"City": "NYC",
	"Make": [{
		"Honda": [{
			"Model": "Accord",
			"Made": "2009",
			"Mileage": 120000
		}, {
			"Model": "Civic",
			"Made": "2017",
			"port": 12000

		"Toyota": {
			"Model": "Camry",
			"Made": "2011",
			"Mileage": 18000

		"Kia": {
			"Model": "Telluride ",
			"Made": "2019",
			"Mileage": 11000

sampleDict = json.loads(dict1)
if 'City' in sampleDict:
    if 'Make' in sampleDict('City'):
        <not sure how to insert the data here>

What I have tried:

I am new to python, and could not able to figure it out.
Updated 15-Sep-22 0:59am

json.loads reads the file into a dictionary: json.loads() in Python - GeeksforGeeks[^]
So all you need to do is add treh new data to that: Python Adding Items in a Dictionary[^]
And save the json back to a file: json.dumps() in Python - GeeksforGeeks[^]
Share this answer
Richard MacCutchan 15-Sep-22 4:16am    
The loads and dumps functions are for processing strings; load and dump are for reading/writing files.
The "Make" item is a list of dictionaries, so you just create a new dictionary with the appropriate keys, and add it to the list. Similarly the "Honda" item is a list of dictionaries, so you can add more models to its list. However, "Toyota" and "Kia" are simple dictionaries rather than lists so you would need to convert them to lists in order to add more models.

You can use the code below to help see the structure of the items:
print('\n   Keys:', sampleDict.keys())
print('\nMake[0]:', sampleDict['Make'][0])
print('\n Toyota:', sampleDict['Make'][0]['Toyota'])
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900