JSON (JavaScriptObjectNotation)
- A JSON is essentially composed of a bunch of nested lists and dictionaries, and it has that key value pair data structure.
- To work with JSON data in Python, we can use the inbuilt JSON library, and we're going to use it to write , read, and update data to a JSON file.
{
"Amazon": {
"email": "[email protected]",
"password": "e76cvXeu+k)orK"
}
}
- Write | json.dump()
- It takes a number of inputs, but the most important are the things you want to dump and the file that you want to dump it to.
- Indent can provide the number of spaces to indent all the JSON data so that it becomes much easier to read.
website = website_input.get()
email = email_input.get()
password = password_input.get()
new_data = {
website: {
"email": email,
"password": password,
}
}
if website == "" or password == "":
messagebox.showinfo(title="Oops", message="Please don't leave any fields empty!")
else:
with open("data.json", "w") as data_file:
json.dump(new_data, data_file, indent=4)
website_input.delete(0, END)
password_input.delete(0, END)
- Read | json.load()
- Pass in the file path is the only required input
- Change from write mode to read mode.
- The load method essentially takes this JSON data and converts it into a Python dictionary.
- So essentially we can use json.dump and json. load to serialize and deserialize from JSON data to Python dictionaries. And it allows us that free interchange of information.
- We change it into a JSON to store it, and then we take it out of storage and turn it into a Python dictionary to easily work with it in our code.
- json.load() method would not work in write mode
with open("data.json", "r") as data_file:
data = json.load(data_file)
print(data)
website_input.delete(0, END)
password_input.delete(0, END)
- Update | json.update()
- We want to update what's existing in there with the new data that's being passed in.
- We have our data loaded up into a dictionary, we use the update method to update that dictionary with some new piece of data.
- So we can split this code into two sections:
- First, we open the file in read mode, we get hold of the data, we update the data
- Then, we open up the file again in write mode. This time we're going to dump the data that we've updated over here into that data file using this particular indent format.
with open("data.json", "r") as data_file:
#Reading old data
data = json.load(data_file)
#Updating old data with new data
data.update(new_data)
with open("data.json", "w") as data_file:
#Saving updated data
json.dump(data, data_file, ident=4)
website_input.delete(0, END)
password_input.delete(0, END)