G
GuideDevOps
Lesson 5 of 15

Working with JSON & YAML

Part of the Python for DevOps tutorial series.

DevOps engineers live in JSON and YAML. From Kubernetes manifests to AWS configurations, being able to programmatically manipulate these formats is a core skill.

1. JSON (JavaScript Object Notation)

Python's built-in json module makes it easy to work with JSON strings and files.

Parse JSON String

Action:

import json
 
json_data = '{"hostname": "web-01", "port": 8080}'
config = json.loads(json_data)
 
print(f"Host: {config['hostname']}")
print(f"Port: {config['port']}")

Result:

Host: web-01
Port: 8080

Write JSON to File

Action:

data = {
    'servers': [
        {'name': 'web-1', 'ip': '10.0.1.1'},
        {'name': 'web-2', 'ip': '10.0.1.2'}
    ]
}
 
with open('config.json', 'w') as f:
    json.dump(data, f, indent=2)
 
# Verify
with open('config.json', 'r') as f:
    print(f.read())

Result:

{
  "servers": [
    {
      "name": "web-1",
      "ip": "10.0.1.1"
    },
    {
      "name": "web-2",
      "ip": "10.0.1.2"
    }
  ]
}

2. YAML (YAML Ain't Markup Language)

YAML is the format of choice for Kubernetes and Ansible. You need the PyYAML package to work with it.

Parse YAML Data

Action:

import yaml
 
yaml_data = """
servers:
  - name: web-1
    ip: 10.0.1.1
  - name: web-2
    ip: 10.0.1.2
"""
 
# Always use safe_load to prevent security risks
config = yaml.safe_load(yaml_data)
 
print(f"First Server: {config['servers'][0]['name']}")

Result:

First Server: web-1

Write YAML to File

Action:

data = {
    'project': 'DevOps Guide',
    'status': 'Active',
    'tags': ['python', 'automation']
}
 
with open('project.yaml', 'w') as f:
    yaml.dump(data, f, default_flow_style=False)
 
# Verify
with open('project.yaml', 'r') as f:
    print(f.read())

Result:

project: DevOps Guide
status: Active
tags:
- python
- automation

Summary

  • Use json.loads() for strings and json.load() for files.
  • Always use yaml.safe_load() instead of yaml.load() for security.
  • JSON is native to Python; YAML requires pip install PyYAML.
  • Use indent=2 in JSON and default_flow_style=False in YAML for human-readable output.