Day Fifteen: Using Python Libraries for DevOps: Parsing JSON and YAML- The #90DaysOfDevOps Challenge

Welcome to Day 15 of the #90DaysOfDevOps challenge! In DevOps, handling various file formats is essential. Parsing JSON, YAML, or other types of files that may be needed. Python, with its rich ecosystem of libraries, offers many options for these tasks. Let's explore how Python libraries handle JSON and YAML files in DevOps workflows.

Parsing JSON with Python:

Python's json module simplifies the process of working with JSON data. As a DevOps Engineer, you'll often encounter scenarios where you must create or parse JSON files. Here's a simple task to illustrate its usage:

import json

# Create a dictionary
data = {
    "aws": "ec2",
    "azure": "VM",
    "gcp": "compute engine"
}

# Write the dictionary to a JSON file
with open('services.json', 'w') as json_file:
    json.dump(data, json_file)

When you run this code and print the contents of services.json you get the result below:

Using the JSON file we wrote to services.json , containing information about cloud services provided by different vendors. We want to extract the service names for each cloud service provider.

import json

# Read the JSON file
with open('services.json', 'r') as json_file:
    services_data = json.load(json_file)

# Print service names for each cloud provider
for provider, service in services_data.items():
    print(f"{provider}: {service}")

Output:

Handling YAML with Python:

YAML is another popular format for configuration files in DevOps. Python's yaml module comes in handy for working with YAML data.

import yaml
import json 

# Read YAML file and convert to JSON
with open('services.yaml', 'r') as yaml_file:
    yaml_data = yaml.safe_load(yaml_file)

# Convert YAML to JSON
json_data = json.dumps(yaml_data)

print(json_data)

By using Python's yaml module, we effortlessly read the contents of a YAML file and converted it to JSON format.

Output:

That concludes our journey for Day 15 of the #90DaysOfDevOps challenge. In summary, today we explored libraries in Python to parse different file types. Stay tuned for more exciting challenges and insights as we continue our DevOps journey together.