Reading JSON and YAML in Python
As a DevOps Engineer you should be able to parse files, be it txt, json, yaml, etc.
You should know what all libraries one should use in Python for DevOps.
Python has numerous libraries like
os
,sys
,json
,yaml
etc that a DevOps Engineer uses in day-to-day tasks.Tasks 1 - Create a Dictionary in Python and write it to a Json File.
Json. Dumps ()To create a dictionary in Python and write it to a JSON file, you can follow these steps:
Create a Dictionary: Define the dictionary with the key-value pairs you want.
Import the
json
Module: This module provides functions to work with JSON data.Write the Dictionary to a JSON File: Use the
json.dump()
function to write the dictionary to a file in JSON format.
Explanation
import json
: This imports the JSON module, which provides functions for working with JSON data.data
: This is a Python dictionary containing various types of data, such as strings, integers, lists, and Booleans.open(file_name, 'w') as file
: This opens a file nameddata.json
in write mode. If the file does not exist, it will be created. If it does exist, it will be overwritten.json.dump(data, file, indent=4)
: This function converts the Python dictionarydata
into a JSON-formatted string and writes it to the filedata.json
. Theindent=4
argument is optional but makes the JSON output more readable by adding indentation.Running the Script
When you run this script, it will create a file named
data.json
in the same directory as your script. The contents ofdata.json
will look like this:Tasks 2 - Read a json file
services.json
kept in this folder and print the service names of every cloud service provider.output
aws : ec2
azure : VM
gcp : compute engine
To accomplish this task, we would typically write a script to read the JSON file and extract the required information.
Here’s a Python script that reads services. Json and prints the service names for each cloud service provider:
Make sure services.json
is structured properly and adjust the JSON parsing if necessary. Here’s a sample JSON structure that the script expects:
Save this Python script to a file and run check you will get below output as expected.
Task 3 - Read YAML file using python, file services.yaml
and read the contents to convert yaml to json
Install Required Libraries
1. First, you need to install PyYAML
if you haven't already:pip install pyyaml
2. Here's the Python code to read the services.yaml
file and convert its contents to JSON:
Explanation:
yaml.safe
_load(file)
: This function reads the YAML file and converts it into a Python dictionary.json.dumps(yaml_data, indent=4)
: This function converts the Python dictionary into a JSON-formatted string with indentation for readability.
Example services.yaml
File Structure:
This script will read the contents of services.yaml
, convert it to JSON format, and print the resulting JSON string and it will save to service.json
Appreciate your visit to my blog. Enjoy your learning experience!"