The json library in Python
1. Encoding Python Data to JSON:
import json
# Python dictionary to be encoded to JSON
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# Encode the Python dictionary to JSON
json_data = json.dumps(data)
print("Encoded JSON:", json_data)
#clcoding.com
Encoded JSON: {"name": "John", "age": 30, "city": "New York"}
2. Decoding JSON to Python Data:
import json
# JSON data to be decoded to Python
json_data = '{"name": "John", "age": 30, "city": "New York"}'
# Decode the JSON data to a Python dictionary
data = json.loads(json_data)
print("Decoded Python Data:", data)
#clcoding.com
Decoded Python Data: {'name': 'John', 'age': 30, 'city': 'New York'}
3. Reading JSON from a File:
clcoding
import json
# Read JSON data from a file
with open('clcoding.json', 'r') as file:
data = json.load(file)
print("JSON Data from File:", data)
#clcoding.com
JSON Data from File: {'We are supporting freely to everyone. Join us for live support. \n\nWhatApp Support: wa.me/919767292502\n\nInstagram Support : https://www.instagram.com/pythonclcoding/\n\nFree program: https://www.clcoding.com/\n\nFree Codes: https://clcoding.quora.com/\n\nFree Support: pythonclcoding@gmail.com\n\nLive Support: https://t.me/pythonclcoding\n\nLike us: https://www.facebook.com/pythonclcoding\n\nJoin us: https://www.facebook.com/groups/pythonclcoding': None}
4. Writing JSON to a File:
import json
# Python dictionary to be written to a JSON file
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# Write the Python dictionary to a JSON file
with open('output.json', 'w') as file:
json.dump(data, file)
#clcoding.com
5. Handling JSON Errors:
import json
# JSON data with syntax error
json_data = '{"name": "John", "age": 30, "city": "New York"'
try:
# Attempt to decode JSON data
data = json.loads(json_data)
except json.JSONDecodeError as e:
# Handle JSON decoding error
print("Error decoding JSON:", e)
#clcoding.com
Error decoding JSON: Expecting ',' delimiter: line 1 column 47 (char 46)
0 Comments:
Post a Comment