This is as close to a dictionary as you can get.
To write to a JSON file, first import json. Next, you should open the JSON file regularly, just like you would with a text file. Create a “dictionary” in which you will put all the data that you will store. Once you’ve put all the data in it, do json.dump((your dictionary name), (the name that you opened the JSON file with), indent = 4). It is recommended that you have indent set to 2 or 4 to improve human readability of the JSON file. Be sure to close the JSON file after writing. If you don’t, it won’t save, just like with text files.
Do not dump several times. Do not dump an object that isn’t a dictionary (you can dump a dictionary that has a list as a key, but not a list).
Basic Outline:
import json
x = open('./testit.json', 'w')
topdict = {}
# add key/value pairs to topdict
json.dump(topdict, x, indent = 4)
x.close()
Example:
import json
x = open('filename.json', 'w')
topdict = {}
chinese = {
"hello" : "ni hao",
"bye" : "zai jian",
"how are you" : "ni hao ma"
}
frenchlist = [34, 1, 2, 6]
topdict["chinese"] = chinese
topdict["frenchlist"] = frenchlist
json.dump(topdict, x, indent = 4)
x.close()
View code on GitHub.
To read from a .json file, first import json. Next, open the JSON file regularly, but in read mode. Next, assign a variable to json.load(filename). Congratulations, that’s all it takes to read a JSON file. You can print it and use it just like a dictionary. For good convention, close the file when you’re done, even if you didn’t write anything.
Basic Outline:
import json
x = open('filename.json', 'r')
y = json.load(x) # y becomes the equivalent of a "top_dict"
Example:
import json
x = open('./testit.json', 'r')
y = json.load(x)
# assuming that testit.json had been written to
for key in y:
print(key, “, “, y[key])
x.close()
View code on GitHub.
To add items to a pre-existing JSON file, you first need to get the JSON file's data. So, follow the steps under "Basic outline" in "Reading". Next, close the file. You are now free to add items or remove items from the dictionary. Then, re-open the file in write mode. Then, following the aforementioned writing conventions, write the updated dictionary onto the JSON file.
Basic Outline