Table of contents
✅Introduction📚
JSON stands for JavaScript Object Notation. It is mainly used for storing and transferring data between the browser and the server.json is language-agnostic, meaning it can be used with any programming language that supports text-based data interchange.JSON data is represented in a structured format i.e. key-value pairs enclosed within curly braces {}
.
{
"name": "John Doe",
"age": 30,
"isStudent": false
}
YAML, which stands for YAML Ain't Markup Language (a recursive acronym), is a human-readable data serialization format. It is often used for configuration files, data exchange between languages with different data structures, and as a more human-friendly alternative to formats like JSON or XML. YAML was designed to be easy for both humans to read and write, and machines to parse and generate.
Here's an explanation of YAML in more detail:
Human-Readable Format: YAML's syntax is designed to be intuitive and visually clear, making it easier for humans to create and modify compared to more verbose formats like XML. It relies on indentation, whitespace, and simple punctuation to define data structures.
Data Structures: YAML supports several basic data structures:
Mappings: Similar to JSON objects, mappings are key-value pairs where keys are separated from values using a colon
:
. Mappings are represented using indentation.Sequences: Similar to JSON arrays, sequences are ordered lists of items, represented using dashes
-
followed by a space.Scalars: Scalars are single values like strings, numbers, booleans, and null. Scalars are not explicitly labeled and are written as is.
Indentation: YAML uses indentation to indicate nesting and structure. Indentation is critical for determining the level of nesting, so consistent and correct indentation is important for valid YAML documents.
Comments: YAML supports comments, which start with the
#
character and extend to the end of the line. Comments are ignored by parsers and are meant for human-readable annotations.Example YAML Document: Here's an example of a YAML document that represents basic information about a person using mappings and sequences:
yamlCopy codename: John Doe age: 30 isStudent: false hobbies: - hiking - reading address: street: 123 Main St city: Exampletown
Use Cases: YAML is commonly used for configuration files in software applications, including web frameworks, build tools, and server setups. It's also used for creating manifests in containerization technologies like Docker and Kubernetes. Additionally, it's used for defining structured content in content management systems and data exchange between systems with different data models.
Complex Structures and Anchors: YAML supports more advanced features such as anchors and aliases, which allow for reusing portions of a YAML document within the same document. This can help reduce redundancy and simplify complex structures.
YAML vs. JSON: Compared to JSON, YAML is often considered more human-readable due to its use of indentation and less strict punctuation. However, YAML can be more prone to formatting errors due to its sensitivity to whitespace and indentation.
✅Create a Dictionary in Python and write it to a JSON File.📁
Step 1: Import the json module
import json
step 2: Create a dictionary
data = {
"name": "achyut das",
"age": 22,
"city": "jagatsinghpur"
}
step 3:Specify the file path for the JSON file
json_file_path = "data.json"
step 4: Write the dictionary to a JSON file
with open(json_file_path, "w") as json_file:
json.dump(data, json_file)
print("Dictionary written to JSON file successfully")
output is :
in this picture, the data.json file was created successfully
inside the data.json file write operation was executed successfully.
✅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
services.json file:
{
"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
}
}
}
code to read the JSON file and execute it to get the service names of every cloud service provider:
#Import the json module
import json
# Specify the file path for the JSON file
json_file_path = "services.json"
# Read the JSON data from the file
with open(json_file_path, "r") as json_file:
data = json.load(json_file)
# Iterate through the services and print provider and service name
for provider, details in data["services"].items():
if provider != "debug":
print(f"{provider} : {details['name']}")
output is:
✅Read YAML file using Python, file services.yaml
and read the contents to convert yaml to json.🖊️
services.yaml :
---
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
code to read the yaml file and convert the yaml file data to JSON file:
#import modules
import yaml
import json
# Open the YAML file for reading
with open('services.yaml','r') as file:
# Load YAML data from the file
yaml_data=yaml.safe_load(file)
# Convert YAML data to JSON format
json_data=json.dumps(yaml_data, indent=4)
# Open a JSON file for writing
with open('output.json','w') as json_file:
# Write the JSON data to the JSON file
json_file.write(json_data)
output is:
the yaml file data was converted to a JSON file successfully.