Python Libraries : JSON & YAML

Python Libraries : JSON & YAML

·

4 min read

Introduction to JSON & YAML🐍

JSON : JavaScript Object Notation

  • JSON is a data format used for structuring data in a readable and lightweight manner.

  • Its primary purpose is to store and transfer data between web browsers and servers.

  • Python also supports JSON through a built-in package called "JSON."

  • The JSON package in Python offers various tools for working with JSON objects, such as parsing, serializing, deserializing, and more.

      # Example
      {
        "name": "John Doe",
        "age": 30,
        "is_student": false,
        "hobbies": ["reading", "painting", "gardening"]
      }
    
  • Convert JSON to python object :

    • json.loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary.

        import json
        # JSON string
        student = '{"id":"20", "name": "Shera", "department":"CS"}'
        print("This is JSON", type(student))
      
        print("\nNow convert from JSON to Python")
      
        # Convert string to Python dict
        student_dict = json.loads(student)
        print("Converted to Python", type(student_dict))
        print(student_dict)
      

  • Convert python object to JSON :

    • Here json.dumps() function will convert a subset of Python objects into a JSON string

        import json
        # JSON string
        student_dict = {'id': '20', 'name': 'Shera', 'department': 'CS'}
        print("This is Python", type(student_dict))
      
        print("\nNow Convert from Python to JSON")
      
        # Convert Python dict to JSON
        json_object = json.dumps(student_dict, indent=4)
        # indent parameter specifies the spaces that are 
        # used at the beginning of a line
        print("Converted to JSON", type(json_object))
        print(json_object)
      

YAML : YAML Ain't Markup Language

  • YAML is a data serialisation format that allows for script interaction. It is commonly used to create configuration files because it prioritises human readability over JSON.

  • Can be installed using pip :

      pip install PyYAML
      # YAML example 
      name: John Doe
      age: 30
      is_student: false
      hobbies:
        - reading
        - painting
        - gardening
    

Hands-On Practice⌨️

Task1 :

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

import json
# Create the employee dictionary
employee = {
    "name": "Kumar Ankit",
    "age": 23,
    "job_title": "Software Engineer",
    "department": "Engineering"
}
# Printing dict data
print("This is Python Dictionary: \n",employee,type(employee))
print("\nNow Convert from Python to JSON")

# Convert Python dict to JSON , serializing json
json_object = json.dumps(employee, indent=4)
# indent parameter specifies the spaces that are
# used at the beginning of a line
print("Converted to JSON", type(json_object))
# Printing json object
print(json_object)

Task 2 :

Read a json file services.json kept in this folder and print the service names of every cloud service provider.

{
    "services": {
      "debug": "on",
      "aws": {
        "name": "EC2",
        "type": "pay per hour",
        "instances": 500,
        "count": 500
      },
      "azure": {
        "name": "VM",
        "type": "pay per hour",
        "instances": 500,
        "count": 500
      },
      "gcp": {
        "name": "Compute Engine",
        "type": "pay per hour",
        "instances": 500,
        "count": 500
      }
    }
  }
# solution 1
# creat a .py file in same directory where json file is stored
import json

with open("services.json","r") as file :
    data = json.loads(file.read())
data['services'].pop('debug')
for k,v in data['services'].items():
    print(k+ ":" +v['name'])

# solution 2
import json
with open("services.json") as s:
    # converting it to python dict
    data = json.load(s)
    print("type: ", type (data))
    print("aws:", data['services']['aws']['name'])
    print("azure:", data['services']['azure']['name'])
    print("gcp:", data['services']['gcp']['name'])

Task 3:

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

---
services:
  debug: 'on'
  aws:
    name: EC2
    type: pay per hour
    instances: 500
    count: 500
  azure:
    name: VM
    type: pay per hour
    instances: 500
    count: 500
  gcp:
    name: Compute Engine
    type: pay per hour
    instances: 500
    count: 500
# yaml.load() function parses and converts a YAML object to a Python dictionary
import yaml
from yaml.loader import SafeLoader
import json

 # Open the YAML file and load its contents
 with open('services.yaml','r') as s:
     data = yaml.load(s , Loader=SafeLoader)
     print(data)
# now convert to dictionaryand then to a json string using json.dumps()
with open('new_json','w') as json_f:
    json.dump(data,json_f)
final_output = json.dumps(json.load(open('new_json')),indent=4)
print("json_file :\n",final_output)

Stay tuned for more updates and more hands-on practice

HAppy Learning :D