Hi ππ
In this post, I will share with you how to add new data to JSON file using Pyhton.
If you have this JSON data in this format, how can we deal with this data in this format? It is not as easy as you think; some programmers, especially beginners, face problems. The problem happened when they started to add new data. In this post, I will share with you an easy way to solve this problem.
This is the JSON file called database.json
{
"tasks": [
{
"name": "signup and earn 0.20$",
"description": "signup and earn money",
"money": 0.2
},
{
"name": "signup and earn 0.10$",
"description": "signup and earn money",
"money": 0.1
},
{
"name": "signup and earn 1.20$",
"description": "signup and earn money",
"money": 1.2
}
]
}
Now i will to add new data to this file
import json
tasks = json.load(open('database.json', 'r'))['tasks']
tasks.append({"name": "test", "description": "2222", "money": 1})
json.dump(tasks, open('database.json', 'w'))
As you can see, the JSON format will be damaged.
[{"name": "signup and earn 0.20$", "description": "signup and earn money", "money": 0.2}, {"name": "signup and earn 0.10$", "description": "signup and earn money", "money": 0.1}, {"name": "signup and earn 1.20$", "description": "signup and earn money", "money": 1.2}, {"name": "test", "description": "2222", "money": 1}]
This happend becuse you write a tasks list to the json file
tasks = json.load(open('database.json', 'r'))['tasks']
print(tasks)
result
[{'name': 'signup and earn 0.20$', 'description': 'signup and earn money', 'money': 0.2}, {'name': 'signup and earn 0.10$', 'description': 'signup and earn money', 'money': 0.1}, {'name': 'signup and earn 1.20$', 'description': 'signup and
earn money', 'money': 1.2}, {'name': 'test', 'description': '2222', 'money': 1}]
To keep the JSON file format
import json
tasks = json.load(open('database.json', 'r'))
tasks['tasks'].append({"name": "test", "description": "2222", "money": 1})
json.dump(tasks, open('database.json', 'w'), indent=4)
result
{
"tasks": [
{
"name": "signup and earn 0.20$",
"description": "signup and earn money",
"money": 0.2
},
{
"name": "signup and earn 0.10$",
"description": "signup and earn money",
"money": 0.1
},
{
"name": "signup and earn 1.20$",
"description": "signup and earn money",
"money": 1.2
},
{
"name": "test",
"description": "2222",
"money": 1
}
]
}
Now we're done π€
Don't forget to like and follow π
Support me on PayPal π€
https://www.paypal.com/paypalme/amr396