JSON Objects in Python – 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))

Source Article