Working with JSON in Python - potatoscript/json GitHub Wiki
π Working with JSON in Python: Unleash the Power of Data! π
Welcome to the Amazing World of JSON and Python! ππ‘
JSON is the go-to format for exchanging data, and Python makes it super easy to handle! ππ
π― What is JSON in Python?
- JSON (JavaScript Object Notation): A lightweight format to store and exchange data.
- Python + JSON: Python provides the
jsonmodule to parse, encode, and manipulate JSON effortlessly! π
π₯ 1. Importing the json Module
Before working with JSON, import the json module.
import json
π 2. Converting JSON to Python (Deserialization/Parsing)
When you receive JSON data from an API or file, itβs in string format. To convert it into a Python object, use:
json.loads() # Convert JSON string to Python object
π― Example: Convert JSON String to Python Dictionary
import json
# JSON string
json_data = '{"name": "Lucy Berry", "age": 26, "hobbies": ["coding", "reading"]}'
# Parse JSON string to Python dictionary
data = json.loads(json_data)
print("Name:", data["name"]) # Lucy Berry
print("Age:", data["age"]) # 26
print("Hobbies:", data["hobbies"]) # ['coding', 'reading']
β Explanation:
json.loads()parses the JSON string into a Python dictionary.- You can access data using key-value pairs.
π© 3. Converting Python to JSON (Serialization/Encoding)
To convert Python objects back to JSON, use:
json.dumps() # Convert Python object to JSON string
π― Example: Convert Python Dictionary to JSON String
import json
# Python dictionary
user_data = {
"name": "Lucy Berry",
"age": 26,
"hobbies": ["coding", "reading"]
}
# Convert Python dictionary to JSON string
json_string = json.dumps(user_data)
print("JSON Data:", json_string)
β Explanation:
json.dumps()converts the Python dictionary into a JSON string.
π 4. Working with JSON Files in Python
π₯ a) Reading JSON from a File
To read JSON from a file and parse it into a Python object:
with open("data.json", "r") as file:
data = json.load(file)
π― Example: Reading JSON File
import json
# Open and read JSON file
with open("user_data.json", "r") as file:
data = json.load(file)
print("User Name:", data["name"])
print("User Age:", data["age"])
β Explanation:
json.load()reads and parses JSON from a file.- The data is now a Python dictionary.
π€ b) Writing JSON to a File
To write Python data to a JSON file:
with open("data.json", "w") as file:
json.dump(data, file)
π― Example: Writing JSON to File
import json
# Python dictionary
user_data = {
"name": "Lucy Berry",
"age": 26,
"hobbies": ["coding", "reading"]
}
# Write data to JSON file
with open("user_data.json", "w") as file:
json.dump(user_data, file, indent=4)
print("Data successfully written to file!")
β Explanation:
json.dump()writes JSON data to a file.indent=4formats the output for better readability.
πΉοΈ 5. Pretty Print JSON in Python
To make JSON more readable, use indent in json.dumps():
π― Example: Pretty Print JSON
import json
# Python dictionary
user_data = {
"name": "Lucy Berry",
"age": 26,
"hobbies": ["coding", "reading"]
}
# Pretty print JSON
pretty_json = json.dumps(user_data, indent=4)
print(pretty_json)
β Explanation:
indent=4makes the JSON easy to read with proper spacing.
π 6. Handling Nested JSON in Python
When you have complex JSON with nested objects or arrays, you can parse them easily.
π― Example: Parsing Nested JSON
import json
# Nested JSON string
nested_json = '''
{
"name": "Lucy Berry",
"address": {
"street": "123 Snoopy Lane",
"city": "Fukuoka",
"country": "Japan"
},
"hobbies": ["coding", "reading"],
"education": [
{"degree": "Bachelors", "year": 2015},
{"degree": "Masters", "year": 2019}
]
}
'''
# Parse nested JSON
data = json.loads(nested_json)
# Access nested objects
print("Street:", data["address"]["street"])
print("City:", data["address"]["city"])
# Access list of objects
for edu in data["education"]:
print(f"{edu['degree']} - {edu['year']}")
β Explanation:
- Nested objects and arrays can be accessed using multiple keys.
- Use loops to iterate through lists.
π§© 7. Converting Python Objects to JSON
json.dumps() works on many Python objects, including:
| π Python Object | π₯ JSON Equivalent |
|---|---|
dict |
Object |
list, tuple |
Array |
str |
String |
int, float |
Number |
True |
true |
False |
false |
None |
null |
π― Example: Convert Different Python Objects to JSON
import json
# Data types to JSON
data = {
"name": "Lucy Berry",
"age": 26,
"isAdmin": True,
"hobbies": ["coding", "reading"],
"pets": None
}
json_string = json.dumps(data, indent=4)
print(json_string)
β Explanation:
- Different Python objects are automatically converted to valid JSON.
π‘ 8. Using JSON in APIs with Python
When interacting with APIs, you often send and receive JSON data.
π― Example: Sending JSON with requests Library
import requests
import json
# API URL
url = "https://api.example.com/users"
# Data to send
data = {
"name": "Lucy Berry",
"age": 26
}
# Send POST request with JSON data
response = requests.post(url, json=data)
# Print server response
print("Response:", response.json())
β Explanation:
requests.post()sends a POST request with JSON.response.json()parses the response.
β‘ 9. Error Handling in JSON with Python
When working with JSON, handle errors gracefully.
π― Example: Handling JSON Parsing Errors
import json
# Invalid JSON string
invalid_json = '{"name": "Lucy", "age": 26,}'
try:
data = json.loads(invalid_json)
print("Parsed Data:", data)
except json.JSONDecodeError as e:
print("Error parsing JSON:", e)
β Explanation:
json.JSONDecodeErrorcatches invalid JSON.- Proper error handling prevents crashes.
π§ 10. Customizing JSON Encoding in Python
You can define how custom objects are converted to JSON.
π― Example: Custom JSON Encoder
import json
# Custom class
class User:
def __init__(self, name, age):
self.name = name
self.age = age
# Custom encoder
class UserEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, User):
return {"name": obj.name, "age": obj.age}
return super().default(obj)
# Create user instance
user = User("Lucy Berry", 26)
# Encode with custom encoder
json_data = json.dumps(user, cls=UserEncoder)
print(json_data)
β Explanation:
UserEncoderdefines how to convertUserobjects to JSON.
π₯ 11. Advanced: JSON Path in Python
To extract specific data from JSON, use the jsonpath library.
π― Example: Using JSONPath
import json
import jsonpath
# JSON data
data = '''
{
"users": [
{"name": "Lucy", "age": 26},
{"name": "Bruce", "age": 35}
]
}
'''
# Parse JSON
parsed_data = json.loads(data)
# Extract all names
names = jsonpath.jsonpath(parsed_data, "$.users[*].name")
print(names) # ['Lucy', 'Bruce']
β Explanation:
$.users[*].nameextracts all names from the JSON.