Python for Network Engineers

How to Read and Write Json Files

by: George El., February 2019, Reading time: 2 minutes

In this post, I will show how to read, write and do operations on json data. I assume the I have the following json file. The first step is to make sure that this is valid json. There are many online validators, this is the one I recommend:

https://jsoneditoronline.org/

This can also prettify you json to make it more readable.

{
  "routers": [
    {
      "name": "R1",
      "IP": "10.0.0.1",
      "vendor": "cisco",
      "model": "881"
    },
    {
      "name": "R2",
      "IP": "10.0.0.2",
      "vendor": "cisco",
      "model": "2911"
    },
    {
      "name": "R3",
      "IP": "10.0.0.3",
      "vendor": "cisco",
      "model": "881"
    }
  ]
}

Reading the File

with open("routers.json", "r") as read_file:
    datajson = json.load(read_file)

the data are converted in a variable datajson, which is a dictionary

Printing the contents

print(datajson)
{'routers': [{'name': 'R1', 'IP': '10.0.0.1', 'vendor': 'cisco', 'model': '881'}, {'name': 'R2', 'IP': '10.0.0.2', 'vendor': 'cisco', 'model': '2911'}, {'name': 'R3', 'IP': '10.0.0.3', 'vendor': 'cisco', 'model': '881'}]}

Make json look pretty

print(json.dumps(datajson, indent=4, sort_keys=True))
{
    "routers": [
        {
            "IP": "10.0.0.1",
            "model": "881",
            "name": "R1",
            "vendor": "cisco"
        },
        {
            "IP": "10.0.0.2",
            "model": "2911",
            "name": "R2",
            "vendor": "cisco"
        },
        {
            "IP": "10.0.0.3",
            "model": "881",
            "name": "R3",
            "vendor": "cisco"
        }
    ]
}

Loop through the Routers

for router in datajson['routers']:
    print (router)
{'name': 'R1', 'IP': '10.0.0.1', 'vendor': 'cisco', 'model': '881'}
{'name': 'R2', 'IP': '10.0.0.2', 'vendor': 'cisco', 'model': '2911'}
{'name': 'R3', 'IP': '10.0.0.3', 'vendor': 'cisco', 'model': '881'}

Sort based on Model

datajson["routers"].sort(key = lambda x: (x['model']))
{'name': 'R2', 'IP': '10.0.0.2', 'vendor': 'cisco', 'model': '2911'}
{'name': 'R1', 'IP': '10.0.0.1', 'vendor': 'cisco', 'model': '881'}
{'name': 'R3', 'IP': '10.0.0.3', 'vendor': 'cisco', 'model': '881'}

Append a router

datajson["routers"].append({'name': 'R4', 'IP': '10.0.0.4', 'vendor': 'cisco', 'model': '3945'})

Remove a router

routers_not_R2 = [router for router in datajson['routers'] if router['name']!='R2']
{'name': 'R1', 'IP': '10.0.0.1', 'vendor': 'cisco', 'model': '881'}
{'name': 'R3', 'IP': '10.0.0.3', 'vendor': 'cisco', 'model': '881'}
{'name': 'R4', 'IP': '10.0.0.4', 'vendor': 'cisco', 'model': '3945'}

Get all 881 routers

routers881 = [router for router in datajson['routers'] if router['model']=='881']
[{'name': 'R1', 'IP': '10.0.0.1', 'vendor': 'cisco', 'model': '881'},
 {'name': 'R3', 'IP': '10.0.0.3', 'vendor': 'cisco', 'model': '881'}]

Get all no 881 routers

routersNot881 = [router for router in datajson['routers'] if router['model']!='881']
[{'name': 'R2', 'IP': '10.0.0.2', 'vendor': 'cisco', 'model': '2911'},
 {'name': 'R4', 'IP': '10.0.0.4', 'vendor': 'cisco', 'model': '3945'}]

Write to File

with open("routers881.json","w",encoding="utf8") as outfile:
    json.dump(routers881, outfile, indent=4)

ouput is

[
    {
        "name": "R1",
        "IP": "10.0.0.1",
        "vendor": "cisco",
        "model": "881"
    },
    {
        "name": "R3",
        "IP": "10.0.0.3",
        "vendor": "cisco",
        "model": "881"
    }
]
comments powered by Disqus