Python JSON Tutorial
JSON (JavaScript Object Notation) is a lightweight data format used for storing and exchanging data. Python provides the json
module to encode and decode JSON data.
1. Importing the JSON Module
Python has a built-in json
module that makes working with JSON easy.
import json
2. Converting Python Data to JSON (Serialization)
Serialization (or encoding) is converting Python objects (dict, list, etc.) into a JSON string using json.dumps()
.
Example: Convert Python Dictionary to JSON
import json
data = {
"name": "Alice",
"age": 25,
"city": "New York"
}
json_data = json.dumps(data, indent=4) # Convert to JSON string
print(json_data)
✅ indent=4
makes JSON readable.
3. Converting JSON to Python Data (Deserialization)
Deserialization (decoding) is converting a JSON string back into a Python object using json.loads()
.
Example: Convert JSON String to Python Dictionary
json_string = '{"name": "Alice", "age": 25, "city": "New York"}'
python_data = json.loads(json_string) # Convert to dictionary
print(python_data["name"]) # Output: Alice
✅ json.loads()
converts JSON string to Python dictionary.
4. Working with JSON Files
4.1 Writing JSON Data to a File
data = {"name": "Alice", "age": 25, "city": "New York"}
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
✅ json.dump()
writes JSON data to a file.
4.2 Reading JSON Data from a File
with open("data.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
✅ json.load()
reads JSON data from a file.
5. Handling Nested JSON Data
JSON data can contain nested objects and lists.
Example: Working with Nested JSON
nested_json = '''
{
"name": "Alice",
"age": 25,
"address": {
"city": "New York",
"zip": "10001"
},
"skills": ["Python", "Django", "Machine Learning"]
}
'''
data = json.loads(nested_json)
print(data["address"]["city"]) # Output: New York
print(data["skills"][0]) # Output: Python
✅ Use indexing to access nested JSON elements.
6. Handling JSON Errors
If JSON is invalid, Python will raise a JSONDecodeError
.
try:
invalid_json = '{"name": "Alice", age: 25}' # Missing quotes around 'age'
data = json.loads(invalid_json)
except json.JSONDecodeError as e:
print("Error:", e)
✅ Always use try-except
when loading JSON to handle errors.
Conclusion
The json
module in Python is useful for storing, exchanging, and processing structured data. It is widely used in APIs, configuration files, and data storage.
0 comments:
Post a Comment