Python JSON Library

This is a tutorial on the Python JSON Library.

What is JSON?

JSON or JavaScript Object Notation has quickly become the new standard for information exchange, commonly used in transferring data across the internet. It’s ease of use and simplicity are signifcant factors in it’s massive popularity.

JSON was derived from the programming language JavaScript. Luckily for us JSON is language independent, so there isn’t any need to know anything about JavaScript beforehand.

In this tutorial we’ll be explaining how to read,parse and (pretty) print JSON data in Python using the JSON library. The JSON library comes bundled with Python natively, so you don’t have to download it separately.


JSON data

Below is a sample of some JSON data. You’ll notice that it has many similarities to Python’s dictionaries and Lists.

{
    "Name": "John Hubbard",
    "Mobile": 1322489439,
    "Married": true,
    "Pets": [
        "Dog",
        "cat"
    ],
    "Address": {
        "Permanent address": "USA",
        "current Address": "AU"
    }
}

We’ll be using this sample data in the upcoming examples when required.


Python to JSON

In this section we’ll be explaining how convert data in Python into JSON. We’ll be doing this with the help of the json.dumps and json.dump functions.

json.dump

The json.dump function is used to write JSON data to a file to be saved in a certain location, like your local storage (hard drive). The below example saves the python data in the variable data into the file called file.json in a JSON format.

with open("file.json", "w") as write_file:
    json.dump(data, write_file)

json.dump takes two parameters, a variable holding the data be converted and the file object which the JSON data is to be written to.

json.dumps

The json.dumps function is similar to json.dump, with the exception that it converts and creates JSON data, but does not save it into a file.

json.dumps(data)

json.dumps takes a single parameters, data and returns the JSON equivalent.

The below table shows you the conversion equivalents when converting from Python to JSON.

PythonJSON equivalent
dictObject
listArray
tupleArray
strString
intNumber
floatNumber
Truetrue
Falsefalse
Nonenull

Pretty printing JSON

While there is a dedicated library in Python for pretty printing, the JSON module has it’s own features that allow us to “pretty” print JSON data in a neat and tidy manner.

json.dumps(data, indent = n, sort_keys = boolean)

The indent parameter decides how many spaces to leave at appropriate sections in the output. sort_keys determines whether the keys should be sorted (alphabetically) or not.

The indent and sort_keys work on both json.dumps and json.dump functions. Just be sure to add them at the end of the pre-existing parameters, not before.

Below is what the output would look if we just used json.dumps(data).

{"Name": "John Hubbard", "Mobile": 1322489439, "Married": true, "Pets": ["Dog", "cat"], "Address": {"Permanent address": "USA", "current Address": "AU"}}

In the example below, we’re going to utilize both the indent and sort_keys parameters to make our JSON output look better.

data = {
  "Name": "John Hubbard",
  "Mobile": 1322489439,
  "Married": True,
  "Pets": ["Dog", "cat"],
  "Address": {
    "Permanent address": "USA",
   "current Address": "AU"
  }
}

print(json.dumps(data, indent=4, sort_keys=True))

The output:

{
    "Address": {
        "Permanent address": "USA",
        "current Address": "AU"
    },
    "Married": true,
    "Mobile": 1322489439,
    "Name": "John Hubbard",
    "Pets": [
        "Dog",
        "cat"
    ]
}

For the indent value, I suggest using values from a range of 3 to 5. Any more or less would not look very presentable.

You can learn more about pretty printing in JSON in a separate dedication tutorial we have.


JSON to Python

In this section we’ll be focusing on how to convert JSON data into Python data. We’ll be using the json.load and json.loads to achieve this task.

Once you’ve downloaded/imported JSON data from whatever source you were using, it’s time to bring it into your python program to use. Before we begin using it though, we’ll have to convert it into a Python format using one of the two functions we mentioned earlier.

Keep in mind that whenever the load function is used, a Python dictionary is returned.

Once you have the data converted, you can then use regular Python methods to retrieve and sort through the data.

json.loads

In the example below, once we’ve converted the data and have returned a Python dictionary, we use the standard keys to return their respective values. Also notice that there can be dictionaries within dictionaries in the JSON and Python data.

import json

data = ''' {
    "Address": {
        "Permanent Address": "USA",
        "current Address": "AU"
    },
    "Married": true,
    "Mobile": 1322489439,
    "Name": "John Hubbard",
    "Pets": [
        "Dog",
        "cat"
    ]
} '''

info = json.loads(data)

print(info["Address"])
print(info["Address"]["Permanent Address"])
print(info["Name"])
{'Permanent Address': 'USA', 'current Address': 'AU'}
USA
John Hubbard

json.load

The json.load is used to “load” the data from a JSON file into the Python program. It takes a single parameter, which is the file object to be read from.

with open("file.json", "w") as read_file:
    data = json.load(read_file)

The JSON data is now loaded into the variable called data.

The below table shows you the conversion equivalents when converting from JSON to Python.

JSONPython
objectdict
arraylist
stringstr
number (int)int
number (real)float
trueTrue
falseFalse
nullNone

This marks the end of the Python JSON Library Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments