6️⃣

20.6 JSON

JSON

This is as close to a dictionary as you can get.

Writing

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.

Reading

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.

Adding/changing items to a pre-existing JSON file

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

import json
x = open('filename.json', 'r')
y = json.load(x) # y becomes the equivalent of a "top_dict"
x.close()
y["some_key"] = "some value" # the value can be all the normal types that dictionaries can hold
x = open("filename.json", "w")
json.dump(y, x, indent = 4)
x.close()

View code on GitHub.

More Methods

Two other methods that may be useful to know are json.dumps() and json.loads() . Although you may be a bit confused, since they are named very similarly to the methods mentioned before, they have different uses.

json.dumps() is a method that creates a string representation of a given Python dictionary. It can be a great asset when you need to print, parse, or perform other tasks with a dictionary that normally wouldn't be possible. This method takes in a dictionary and outputs a string.

Example:

import json

oldDict = {"fname":"john",
					"lname":"doe",
					"age":20}

print("oldDict:", type(oldDict)) #prints data type of oldDict

newStr = json.dumps(oldDict) #converts oldDict to string format

print("newStr:", type(newStr)) #prints data type of newStr

Output:

oldDict: <class 'dict'>
newStr: <class 'str'>

As you can see, the code above converted a Python dictionary to a string.

json.loads() is the opposite of json.dumps() . Instead of converting a dictionary to a string, it converts a string to a dictionary. This method is great for when you have a JSON formatted string and want to turn it into an actual dictionary.

Example:

import json

oldStr = '{"fname":"john","lname":"doe","age":20}'

print("oldStr:", type(oldStr)) #prints data type of oldStr

newDict = json.loads(oldStr) #converts oldStr to string format

print("newDict:", type(newDict)) #prints data type of newDict

Output:

oldStr: <class 'str'>
newDict: <class 'dict'>

If the string does not contain a properly formatted dictionary, an error will be raised

View code on GitHub.

Practice

JSON Practice 1

Use the "favorite_foods.json". In that JSON file, there will be a dictionary called "favorite_foods". Print all the unique favorite foods, which will be the values. Save all the names into a list. Add that list to the dictionary ('names' should be the key and the names list should be the corresponding value) and write the dictionary into the JSON file.

JSON Practice 2

Use the file "wildlife.json". Load the data in the JSON file. Add at least one habitat and corresponding animal(s) to the dictionary. Finally, write the updated dictionary to the JSON file.

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.