Parsing JSON and XML data with Python

JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) are two commonly used data formats for exchanging data between applications and services, including network devices and management systems. Python provides built-in libraries for parsing and processing both JSON and XML data, making it easy to work with these formats in your network automation scripts.

Here’s an example of how to parse JSON data in Python using the built-in json library:

import json

# Example JSON data
json_data = '''
{
  "name": "Switch1",
  "status": "OK",
  "ports": [
    {
      "name": "Port1",
      "status": "UP",
      "speed": "1G"
    },
    {
      "name": "Port2",
      "status": "DOWN",
      "speed": "1G"
    }
  ]
}
'''

# Parse the JSON data into a Python object
data = json.loads(json_data)

# Access and print data from the object
print("Device name:", data["name"])
print("Device status:", data["status"])
print("Number of ports:", len(data["ports"]))

for port in data["ports"]:
    print("Port name:", port["name"])
    print("Port status:", port["status"])
    print("Port speed:", port["speed"])

In this example, we’re using the json library to parse the example JSON data into a Python object. We can then access the different elements of the object and print them to the console.

Here’s an example of how to parse XML data in Python using the built-in xml.etree.ElementTree library:

import xml.etree.ElementTree as ET

# Example XML data
xml_data = '''
<device>
  <name>Switch1</name>
  <status>OK</status>
  <ports>
    <port>
      <name>Port1</name>
      <status>UP</status>
      <speed>1G</speed>
    </port>
    <port>
      <name>Port2</name>
      <status>DOWN</status>
      <speed>1G</speed>
    </port>
  </ports>
</device>
'''

# Parse the XML data into an ElementTree object
root = ET.fromstring(xml_data)

# Access and print data from the object
print("Device name:", root.find("name").text)
print("Device status:", root.find("status").text)
print("Number of ports:", len(root.findall(".//port")))

for port in root.findall(".//port"):
    print("Port name:", port.find("name").text)
    print("Port status:", port.find("status").text)
    print("Port speed:", port.find("speed").text)

In this example, we’re using the xml.etree.ElementTree library to parse the example XML data into an ElementTree object. We can then access the different elements of the object and print them to the console.

Overall, Python provides powerful built-in libraries for parsing and processing both JSON and XML data, making it easy to work with these formats in your network automation scripts.

Leave a Reply