AutoNetOps

Cover Image for Quick and Dirty Python JSON Module For Network Engineers

Quick and Dirty Python JSON Module For Network Engineers

2 min read

Why JSON?

JSON is very popular with Network engineers because many of the APIs and network devices already support it, it is easy to read and maps directly to Python objects.

When we gather information on network devices or store information in files, we need a way to load and push data for treatment in our code.

We can convert a Python variable to a JSON object and a JSON string to a Python structure for use in your code. To do this, you need to import the json module.

import json

Load vs Loads

json.load()

Takes a file object and returns the JSON object. It is used to read JSON-encoded data from a file and convert it into a Python dictionary.

import json

# Sample JSON data saved in a file named 'network_devices.json'
# The content of 'network_devices.json' should look like this:
# [
#     {
#         "device_name": "Router1",
#         "ip_address": "192.168.1.1",
#         "status": "active"
#     },
#     {
#         "device_name": "Switch1",
#         "ip_address": "192.168.1.2",
#         "status": "inactive"
#     }
# ]

# Read JSON data from the file
with open('network_devices.json', 'r') as file:
    network_devices = json.load(file)

# Print the Python object
print(network_devices)

json.loads()

Accepts as input a valid string and converts it to a Python list or dictionary. json.loads(str) -> (dict,list)

import json

network_devices= '''
[
    {
        "device_name": "Router1",
        "ip_address": "192.168.1.1",
        "status": "active"
    },
    {
        "device_name": "Switch1",
        "ip_address": "192.168.1.2",
        "status": "inactive"
    }
]
'''
# Convert JSON string to Python object
network_devices = json.loads(network_devices)

# Print
print(network_devices)

Dump vs Dumps

json.dumps()

Convert a Python object into a JSON string. It accepts:

  • Dict and List

json.dumps(dict, indent)

import json

# Python object with network devices information
network_devices = [
    {
        "device_name": "Router1",
        "ip_address": "192.168.1.1",
        "status": "active"
    },
    {
        "device_name": "Switch1",
        "ip_address": "192.168.1.2",
        "status": "inactive"
    }
]

# Convert Python object to JSON string
network_devices_json = json.dumps(network_devices, indent=2)

# Print the JSON string
print(network_devices_json)

json.dump()

Used for writing to JSON file.

json.dump(dict, file_pointer)

import json

# Python object with network devices information
network_devices = [
    {
        "device_name": "Router1",
        "ip_address": "192.168.1.1",
        "status": "active"
    },
    {
        "device_name": "Switch1",
        "ip_address": "192.168.1.2",
        "status": "inactive"
    }
]

# Write JSON data to a file
with open('network_devices.json', 'w') as file:
    json.dump(network_devices, file, indent=4)