Let's explore most widely used libraries in Python for handling data serialization and deserialization tasks
JSON (JavaScript Object Notation):
Library Name:
json
Purpose: The
json
library in Python provides functions to encode Python objects as JSON strings and decode JSON strings into Python objects. It facilitates the serialization and deserialization of data in JSON format, which is commonly used for data interchange between systems.Usage:
json.dumps()
: Serialize Python object to a JSON formatted string.json.loads()
: Deserialize JSON formatted string to a Python object.json.dump()
: Write JSON data to a file.json.load()
: Read JSON data from a file.
Example: Used for working with web APIs, storing configuration data, and exchanging data between different programming languages and platforms.
YAML (YAML Ain't Markup Language):
Library Name:
pyyaml
(Python YAML)Purpose: The
pyyaml
library in Python allows reading and writing data in YAML format. YAML is a human-readable data serialization format that is often used for configuration files and data exchange between systems, especially in situations where readability by humans is important.Usage:
Example: Commonly used for configuration files, specifying data structures, and documenting data formats in a readable manner.
Let's see these commands in action:
Creating a Dictionary and write it to a JSON File
import json
# Creating a dictionary
services = {
"aws": "ec2",
"azure": "VM",
"gcp": "compute engine"
}
# Writing the dictionary to a JSON file
with open("services.json", "w") as json_file:
json.dump(services, json_file)
print("Dictionary has been written to services.json.")
Output:
JSON file has been created now let's see how to access and read this file
# Reading the JSON file
with open("services.json", "r") as json_file:
services_data = json.load(json_file)
# Printing service names of every cloud service provider
for provider, service in services_data.items():
print(f"{provider} : {service}")
Output:
Read YAML file using python, file services.yaml
and read the contents to convert yaml to json
Before executing this, make sure you have the pyyaml
library installed (pip install pyyaml
)
import yaml
# Reading YAML file and converting to JSON
with open("services.yaml", "r") as yaml_file:
services_yaml = yaml.safe_load(yaml_file)
# Printing JSON content
print(json.dumps(services_yaml, indent=4))
Output:
To summarize
JSON is more commonly used for machine-to-machine communication due to its simplicity and ubiquity.
YAML is often preferred for human-readable data storage and configuration files.