Sunday, 17 October 2021

DevNet - Parsing data formats in Pyton: JSON & YAML (basics)

JSON data code example.

- JSON file:



{ "node": 

  { "hostname": "Edge1", "details": { "interface":

   { "name": "Ethernet0", "description": "L2 Uplink", "enabled": "true"

   }

                                    }

  }

  }


- Python file:


#!/usr/bin/env python

""" simple code to parse json """

import json

with open("data.json", "r", encoding = "UTF-8") as file:

    data = json.load(file)

    print(data)


- Output: 


python parse_json.py

{'node': {'hostname': 'Edge1', 'details': {'interface': {'name': 'Ethernet0', 'description': 'L2 Uplink', 'enabled': ‘true'}}}}


*** of course we can narrow the output information by modifying print command to for instance:


print(data['node']['hostname'])


which would return only the hostname:

python parse_json.py

Edge1


*** there are four ways to be used when parsing data:
    - load() - import native JSON as Python dictionary 
    - loads() - import JSON data from the string
    - dump() - used to write JSON data from python objects into JSON file
    - dumps() - same as dump() except returns string, does not require file object

YAML example:

- YAML file:

cat data.yaml  

---

device:

    hostname: Edge1

    interface:

        name:Ethernet0

        description:Uplink

        enabled:true

...


- Python file:


cat parse_yaml.py 

""" parse YAML file simple example """

import yaml


with open ("data.yaml", "r", encoding = "UTF-8") as fdata:

    ydata = yaml.safe_load(fdata)

    print(ydata)



- Output


python parse_yaml.py

{'device': {'hostname': 'Edge1', 'interface': 'name:Ethernet0 description:Uplink enabled:true’}}


*** two functions are available with in YAML module:

   - yaml.load - to convert YAML data into Python
   - yaml.dump - to convert Python data back to YAML

-----

All files are available on my GitHub: https://github.com/lightarchivist/DevNetLabs

No comments:

Post a Comment

Plumbing... QoS

Rule no 1. QoS does not help in situations where there is no enough bandwidth but helps optimize performance by prioritization of the traffi...