Python Libraries for DevOps

Python Libraries for DevOps

What is a JSON file?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is a text-based format that is commonly used for exchanging data between a client and a server or between different applications.

JSON data is represented in key-value pairs, where each key is a string enclosed in double quotes, followed by a colon, and then a value. The value can be a string, number, boolean, null, array (enclosed in square brackets), or an object (enclosed in curly braces).

Example of JSON data:

{
   "name": "Rajani",
   "age": 25,
   "email": "rajani@gmail.com",
   "isEmployed": true,
   "hobbies": ["treking", "painting"]
   }

What is a YAML file?

YAML (YAML Ain't Markup Language) is a human-readable data serialization format that is commonly used for configuration files and data exchange between applications. It is designed to be easy to read and write for humans and is often used as a replacement for XML or JSON.

YAML data is represented using indentation to indicate nested structures and uses colons and dashes to define key-value pairs and lists, respectively. It supports various data types such as strings, numbers, booleans, null, lists, and dictionaries. Here's an example of YAML data:

name: Rajani
age: 25
email: rajani@gmail.com
isEmployed: true
hobbies:
  - treking
  - painting

YAML files have a .yaml or .yml file extension and can be easily read and written using programming languages such as Python, Ruby, Java, and many others. YAML is often used for configuration files of applications and tools, and for storing data that has a complex, nested structure.

Reading JSON and YAML files in Python is a common task when working with data. Fortunately, Python provides built-in libraries to handle both formats.

Here's how to read a JSON file in Python:

pythonCopy codeimport json

# Open the file containing the JSON data
with open('data.json') as f:
    # Load the JSON data into a dictionary
    data = json.load(f)

# Access the data as you would with any dictionary
print(data['key'])

And here's how to read a YAML file in Python:

pythonCopy codeimport yaml

# Open the file containing the YAML data
with open('data.yaml') as f:
    # Load the YAML data into a dictionary
    data = yaml.load(f, Loader=yaml.FullLoader)

# Access the data as you would with any dictionary
print(data['key'])

Note that for YAML, you need to specify the loader (in this case FullLoader) as a parameter to the yaml.load() function. This is a security measure to prevent arbitrary code execution in YAML files.

Tasks 1:Create a Dictionary in Python and write it to a json File.

import json

data = {
    'name': 'Rajani',
    'age': 25,
    'email': 'rajani@gmail.com',
    'isEmployed': True,
    'hobbies': ['treking', 'painting']
    }

with open('data.json', 'w') as f:
    json.dump(data, f)

print("Data written to JSON file successfully!")
[pavan@localhost Documents]$ python3 python.py 
Data written to JSON file successfully!

Task 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

import json

with open('services.json') as f:
    data = json.load(f)


for provider in data['cloudProviders']:
    print(provider['name'] + " : " + " ".join([service['name'] for service in provider['services']]))

Assuming the services.json file contains data in the following format:

{
  "cloudProviders": [
    {
      "name": "aws",
      "services": [
        {
          "name": "ec2"
        },
        {
          "name": "lambda"
        },
        {
          "name": "s3"
        }
      ]
    },
    {
      "name": "azure",
      "services": [
        {
          "name": "VM"
        },
        {
          "name": "app services"
        },
        {
          "name": "storage"
        }
      ]
    },
    {
      "name": "gcp",
      "services": [
        {
          "name": "compute engine"
        },
        {
          "name": "cloud storage"
        },
        {
          "name": "cloud functions"
        }
      ]
    }
  ]
}

This code will output:

pavan@localhost Documents]$ python3 python.py 
aws : ec2 lambda s3
azure : VM app services storage
gcp : compute engine cloud storage cloud functions

Task 3:Read YAML file using python, file services.yaml and read the contents to convert yaml to json

import yaml
import json

with open('services.yaml') as f:

    data = yaml.safe_load(f)

json_data = json.dumps(data)

print(json_data)

In this example, we open the services.yaml file using the open() function and load its contents into a Python dictionary using the yaml.safe_load() function. Then, we convert the dictionary to a JSON string using the json.dumps() function and store it in the json_data variable. Finally, we print the JSON data to the console.

Assuming the services.yaml file contains data in the following format:

cloudProviders:
  - name: aws
    services:
      - name: ec2
      - name: lambda
      - name: s3
  - name: azure
    services:
      - name: VM
      - name: app services
      - name: storage
  - name: gcp
    services:
      - name: compute engine
      - name: cloud storage
      - name: cloud functions

This code will output the following JSON string:

[pavan@localhost Documents]$ python3 python.py 
{"cloudProviders": [{"name": "aws", "services": [{"name": "ec2"}, {"name": "lambda"}, {"name": "s3"}]}, {"name": "azure", "services": [{"name": "VM"}, {"name": "app services"}, {"name": "storage"}]}, {"name": "gcp", "services": [{"name": "compute engine"}, {"name": "cloud storage"}, {"name": "cloud functions"}]}]}

#json #yaml #python #Devops

Please free to write your thoughts and can connect with me on LinkedIn