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+'))
my_data.json
[{"name": "Test123", "age": 20}]
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)
result
[{"name": "Test123", "age": 20}]
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'))
result in my_data.json
[{"name": "Test123", "age": 20}, {"name": "amr", "age": 22}]
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)
result
[{'name': 'Test', 'age': 20}, {'name': 'amr', 'age': 22}]
Update JSON file
data = json.load(open('my_data.json', 'r'))
data[0]['name'] = 'Test'
json.dump(data, open('my_data.json', 'w'))
result in my_data.json
[{"name": "Test", "age": 20}, {"name": "amr", "age": 22}]
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)
result
[{'name': 'amr', 'age': 22}]
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'))
result in my_data.json
[{'name': 'amr', 'age': 22}]
Now we're done ๐ค
Don't forget to like and follow ๐
Support me on PayPal ๐ค
https://www.paypal.com/paypalme/amr396