add, update, and delete data in a JSON file using Python

Free Python Code - Aug 26 '23 - - Dev Community

Hi 🙂🖐

Welcome to a new article. Today I will share with you how to deal with JSON files using Python and a built-in module called json.

Save data to JSON file

Create a new JSON file and save some data to it using a function called dump that will convert objects like dicts or lists to JSON format.


import json

data = [
    {'name': 'Test123','age': 20}
]

json.dump(data, open('my_data.json', 'a+'))

Enter fullscreen mode Exit fullscreen mode

my_data.json

[{"name": "Test123", "age": 20}]
Enter fullscreen mode Exit fullscreen mode

Load data from JSON file

To load data from a JSON file, you can use the load function, which will return the same data type you used before.

data = json.load(open('my_data.json'))
print(data)
Enter fullscreen mode Exit fullscreen mode

result

[{"name": "Test123", "age": 20}]
Enter fullscreen mode Exit fullscreen mode

add new data to JSON file

To add new data to a JSON file, you need to load it first and save it into a variable.

data = json.load(open('my_data.json', 'r'))
# append new data to list
data.append({'name': 'amr', 'age': 22})

json.dump(data, open('my_data.json', 'w'))
Enter fullscreen mode Exit fullscreen mode

result in my_data.json

[{"name": "Test123", "age": 20}, {"name": "amr", "age": 22}]
Enter fullscreen mode Exit fullscreen mode

update data in JSON file

select the first dict and change the name To Test

data = json.load(open('my_data.json', 'r'))
data[0]['name'] = 'Test'

print(data)
Enter fullscreen mode Exit fullscreen mode

result

[{'name': 'Test', 'age': 20}, {'name': 'amr', 'age': 22}]
Enter fullscreen mode Exit fullscreen mode

Update JSON file

data = json.load(open('my_data.json', 'r'))
data[0]['name'] = 'Test'

json.dump(data, open('my_data.json', 'w'))
Enter fullscreen mode Exit fullscreen mode

result in my_data.json

[{"name": "Test", "age": 20}, {"name": "amr", "age": 22}]
Enter fullscreen mode Exit fullscreen mode

delete data from JSON file


data = json.load(open('my_data.json', 'r'))

for d in data:
    if d['name'] == 'Test':
        data.remove(d)

print(data)

Enter fullscreen mode Exit fullscreen mode

result

[{'name': 'amr', 'age': 22}]
Enter fullscreen mode Exit fullscreen mode

Apply changes on JSON file

data = json.load(open('my_data.json', 'r'))

for d in data:
    if d['name'] == 'Test':
        data.remove(d)

json.dump(data, open('my_data.json', 'w'))
Enter fullscreen mode Exit fullscreen mode

result in my_data.json

[{'name': 'amr', 'age': 22}]
Enter fullscreen mode Exit fullscreen mode

Now we're done 🤗

Don't forget to like and follow 🙂

Support me on PayPal 🤗
https://www.paypal.com/paypalme/amr396

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .