JSON Objects in Python. Introduction to JSON objects in Python | by Sadrach Pierre, Ph.D. | Towards Data Science

Java Script Object Notation (JSON) is a light weight data format with many similarities to python dictionaries. JSON objects are useful because browsers can quickly parse them, which is ideal for transporting data between a client and a server. In this post, we will discuss how to use python’s JSON library to send and receive JSON data.
Let’s get started!
First, let’s inspect the following JSON packet with information about The Beatle’s album Yellow Submarine :
{     "album_title" : "Yellow Submarine",          "release_year" : 1966,        "won_grammy" : false,     "band" : "The Beatles",     "album_sale": null     "musicians" : ["John Lennon", "Paul McCartney", "George   Harrison", "Ringo Starr"],     "studio" : {"studio_name": "Abbey Road Studios", "location": "London, England"}     }
In JSON objects, the keys are strings and the values can be strings, numbers (floats or ints), boolean values, lists, null, or another JSON object. There are a few differences between python dictionaries and JSON objects that can be discerned from this example. For example, boolean values are lower case and ‘None’ values are ‘null’. A python dictionary equivalent is:
{     "album_title" : "Yellow Submarine",          "release_year" : 1966,        "won_grammy" : False,     "band" : "The Beatles",     "album_sale": None     "musicians" : ["John Lennon", "Paul McCartney", "George   Harrison", "Ringo Starr"],     "studio" : {"studio_name": "Abbey Road Studios", "location": "London, England"}     }
Now, let’s save the sample JSON data to a text file called ‘album.txt’. I did this using a terminal command line and the ‘vim’ text editor, but you can use any tool of you’d like. Next, in a python script, let’s import the JSON module:
import json
Let’s look at the methods available in this module using the ‘dir()’ method:
print(dir(json))
We will be focusing on the load and dump methods. To proceed, let’s use the open method to open the file. In the open method, let’s specify the filename, ‘album.txt’, and the mode (read or write). We will be reading the file so the mode is ‘r’:
album_json_file = open("album.txt", "r")
Next, we can use the load method to load the JSON data from our file:
album = json.load(album_json_file)
After loading the JSON data, we close the file:
album_json_file.close()
We can now print our loaded JSON data:
print(album)
If we print the type of this object we see that it is a python dictionary:
print(type(album))
Let’s look at the differences between the JSON object and the python dictionary. The ‘won_grammy’ value in the JSON object is ‘false’, while in the dictionary it is a capitalized ‘False’. Additionally, the ‘album_sale’ ‘value Null’ was parsed as ‘None’ in the python dictionary.
Now that we've loaded our data as a dictionary, we can access the values in the parsed dictionary by key. For example, if we like to access the ‘album_title’ we do the following:
print("Album Title: ", album['album_title'])
Or if we’d like to access the year the album was released:
print("Release Year: ", album['release_year'])
In client server applications it is common for JSON objects to arrive in the form of strings. For example, our JSON object for album information can look something like this:
album_string = """{"album_title" : "Yellow Submarine",     "release_year" : 1966,     "won_grammy" : false,     "band" : "The Beatles",     "album_sale": null,     "musicians" : ["John Lennon", "Paul McCartney", "George   Harrison", "Ringo Starr"],     "studio" : {"studio_name": "Abbey Road Studios", "location": "London, England"}     }"""
To load this data using the JSON module, we use the ‘loads()’ method:
album_s = json.loads(album_string)album_string.close()print(album_s)
Now, suppose we start with dictionary formatted data and wish to send this data to a database in JSON format. We can use the dumps methods to convert dictionaries to string JSON objects. Let’s define our original dictionary:
album2 = {'album_title': 'Yellow Submarine', 'release_year': 1966, 'won_grammy': False,  'band': 'The Beatles', 'album_sale': None, 'musicians': ['John Lennon', 'Paul McCartney', 'George   Harrison', 'Ringo Starr'],  'studio': {'studio_name': 'Abbey Road Studios', 'location': 'London, England'}}
Next, let’s print the string JSON object using the dumps method:
print(json.dumps(album2))print(type(json.dumps(album2)))
Our dictionary was correctly parsed as a string JSON object. We see that the ‘album_sale’ value, ‘None’, is now ‘null’ and the ‘won_grammy’ value, ‘False’, is now ‘false’.
Finally, we can write this JSON object to a ‘.txt’ file using the dump method:
file2 = open("album2.txt", "w")json.dump(album2, file2)
I’ll stop here but feel free to play around with the code yourself.
To summarize, in this post we discussed how to send and receive JSON data using the python JSON library. We discussed the load methods, which help us receive data and the dump methods which help us send data. If you are interested in learning more about working with JSON objects in python, I recommend Socratica’s YouTube tutorials. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!