Import JSON module

To work with JSON data (string or JSON file), first, it has to be 'translated' into the python data structure. In this lesson, we are going to use python's built-in module json to do it.

import json

Parse JSON in Python

There are a few python methods used to load json data:

  • load(): This method loads data from a JSON file into a python dictionary.
  • loads(): This method loads data from a JSON variable into a python dictionary.
  • dump(): This method loads data from the python dictionary to the JSON file.
  • dumps(): This method loads data from the python dictionary to the JSON variable.

For this example we are going to use the follwoing json data save as 'example.json' in our python working directory.

{
   "hostname":"Router1",
   "uptime":12332,
   "interfaces":[
      {
         "name":"GigabitEthernet0/1",
         "address":"10.1.1.1",
         "speed":1000,
         "operational":true
      },
      {
         "name":"GigabitEthernet0/2",
         "address":"192.168.1.1",
         "speed":100,
         "operational":true
      },
      {
         "name":"GigabitEthernet1/2",
         "address":"172.16.1.1",
         "speed":1000,
         "operational":true
      },
      {
         "name":"GigabitEthernet0/3",
         "address":"10.5.5.1",
         "speed":1000,
         "operational":true
      }
   ]
}

json.load()

Usually, in real life, you are not going to need to parse JSON from within a python script. You will need to parse it from an external json file. So let's look at the following example.

with open('example.json') as f:
    data = json.load(f)

The with statement is a python control-flow structure that simplifies the process of reading and closing the file. Note that we use the load method instead of loads because this is a file.

Let's see what the loaded data looks like in Python:

Parsed JSON data Note that the JSON object is loaded as dictionary in Python. The hostname is loaded as string, uptime as int, interface array as list and so on.

Here is a table showing JSON objects and their equivalent conversion to Python.

JSON Python equivalent
object dict
array list, tuple
number int
string str
true True
null None