
Hello, I am sumit and currently pursing my final year of graduation with IT stream from JSPM BSIOTR Wagholi Pune. I am currently learning DevOps with TrainWIthShubham. I have prior knowledge of Java, JSP, Servlet, SQL and Data structure also.I am a hard worker, smart and quick learner.
Reading JSON in Python:
JSON (JavaScript Object Notation): JSON 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 format that is completely language-independent but uses conventions that are familiar to programmers of the C family of languages.
Python json module: Python's json module provides methods for encoding and decoding JSON data. Here are some key functions:
json.loads(): This function is used to parse a JSON string and convert it into a Python dictionary.pythonCopy codeimport json json_data = '{"name": "John", "age": 30, "city": "New York"}' data = json.loads(json_data)json.load(): This function is used to read JSON data from a file and convert it into a Python dictionary.pythonCopy codeimport json with open('path/to/your/file.json', 'r') as file: data = json.load(file)
Reading YAML in Python:
YAML (YAML Ain't Markup Language): YAML is a human-readable data serialization format. It is often used for configuration files and data exchange between languages with different data structures. YAML is more readable than JSON due to its indentation-based structure.
PyYAML Library: PyYAML is a Python library for YAML. To use it, you need to install it first:
bashCopy codepip install PyYAML
yaml.safe_load(): This function is used to parse a YAML string and convert it into a Python dictionary safely.pythonCopy codeimport yaml yaml_data = """ name: John age: 30 city: New York """ data = yaml.safe_load(yaml_data)yaml.safe_load(file): This function is used to read YAML data from a file and convert it into a Python dictionary safely.pythonCopy codeimport yaml with open('path/to/your/file.yaml', 'r') as file: data = yaml.safe_load(file)
Both JSON and YAML are widely used for configuration files, data exchange between different systems, and representing complex data structures in a human-readable format. Depending on your use case and preferences, you may choose one format over the other.
Tasks:
- Create a Dictionary in Python and write it to a json File.
pythonCopy codeimport json
# Create a dictionary
my_dict = {
"name": "John",
"age": 30,
"city": "New York",
"is_student": False,
"grades": [95, 88, 75]
}
# Specify the path for the JSON file
json_file_path = 'path/to/your/output/file.json'
# Write the dictionary to a JSON file
with open(json_file_path, 'w') as json_file:
json.dump(my_dict, json_file, indent=2)
print(f"Dictionary has been written to {json_file_path}")
Explanation:
Create a Dictionary:
- In this example, we create a dictionary called
my_dictwith various key-value pairs, including strings, integers, a boolean, and a list.
- In this example, we create a dictionary called
Specify the JSON File Path:
- Specify the path where you want to save the JSON file. Replace
'path/to/your/output/file.json'with the actual path and filename you want.
- Specify the path where you want to save the JSON file. Replace
Write the Dictionary to a JSON File:
Open the specified JSON file in write mode (
'w').Use the
json.dump()function to write the dictionary to the JSON file. Theindentparameter is optional but adds indentation to make the file more human-readable.
Print Confirmation:
- Print a confirmation message indicating that the dictionary has been written to the JSON file.
After running this script, you should find a JSON file at the specified path containing the data from the dictionary in a JSON format.
- Read a json file
services.jsonkept in this folder and print the service names of every cloud service provider.
Assuming the structure of services.json is something like:
jsonCopy code{
"cloud_providers": [
{
"name": "AWS",
"services": ["EC2", "S3", "Lambda"]
},
{
"name": "Azure",
"services": ["VM", "Blob Storage", "Azure Functions"]
},
{
"name": "Google Cloud",
"services": ["Compute Engine", "Cloud Storage", "Cloud Functions"]
}
]
}
Here's the Python script:
pythonCopy codeimport json
# Specify the path to the JSON file
json_file_path = 'services.json'
# Read the JSON file
with open(json_file_path, 'r') as json_file:
data = json.load(json_file)
# Extract and print service names for each cloud provider
for provider in data.get('cloud_providers', []):
provider_name = provider.get('name')
service_names = provider.get('services', [])
print(f"Services for {provider_name}: {', '.join(service_names)}")
Make sure to replace 'services.json' with the actual path to your services.json file. The script reads the JSON file, extracts information about each cloud provider, and prints the service names associated with each one.
- Read YAML file using python, file
services.yamland read the contents to convert yaml to json
To read a YAML file named services.yaml using Python and convert its contents to JSON, you can use the PyYAML library to parse the YAML and then use the json module to convert it to JSON. Here's an example script:
Assuming the structure of services.yaml is something like:
yamlCopy codecloud_providers:
- name: AWS
services:
- EC2
- S3
- Lambda
- name: Azure
services:
- VM
- Blob Storage
- Azure Functions
- name: Google Cloud
services:
- Compute Engine
- Cloud Storage
- Cloud Functions
Here's the Python script:
pythonCopy codeimport yaml
import json
# Specify the path to the YAML file
yaml_file_path = 'services.yaml'
# Read the YAML file
with open(yaml_file_path, 'r') as yaml_file:
data = yaml.safe_load(yaml_file)
# Convert YAML data to JSON
json_data = json.dumps(data, indent=2)
# Print the JSON data
print("Converted JSON:")
print(json_data)
Make sure to replace 'services.yaml' with the actual path to your services.yaml file. This script reads the YAML file using PyYAML and then uses the json.dumps() function to convert the loaded YAML data to JSON. The resulting JSON data is then printed to the console.




