The json
module in Python is used to work with JSON (JavaScript Object Notation) data. JSON is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. Python’s json
module provides functions to convert between Python objects and JSON.
Why Use JSON?
JSON is commonly used to:
- Exchange data between a server and a web application.
- Store structured data (e.g., configurations or logs).
- Share data between different programming languages.
Importing the json
Module
import json
Converting Python Objects to JSON
The process of converting a Python object into a JSON string is called serialization or encoding. Use the json.dumps()
method.
Supported Python Data Types for JSON Conversion:
Python Data Type | JSON Equivalent |
---|---|
dict | Object |
list , tuple | Array |
str | String |
int , float | Number |
True | true |
False | false |
None | null |
Example: Convert Python Object to JSON
import json
# Python object (dictionary)
data = {"name": "Alice", "age": 25, "isStudent": False}
# Convert to JSON string
json_string = json.dumps(data)
print(json_string)
# Output: {"name": "Alice", "age": 25, "isStudent": false}
Formatting JSON Output
You can pretty-print JSON with formatting options like indentation.
# Pretty-printed JSON
formatted_json = json.dumps(data, indent=4)
print(formatted_json)
Sorting Keys
You can sort the keys in the JSON output using sort_keys=True
.
sorted_json = json.dumps(data, indent=4, sort_keys=True)
print(sorted_json)
Converting JSON to Python Objects
The process of converting a JSON string into a Python object is called deserialization or decoding. Use the json.loads()
method.
Example: Convert JSON to Python Object
import json
# JSON string
json_string = '{"name": "Alice", "age": 25, "isStudent": false}'
# Convert to Python dictionary
data = json.loads(json_string)
print(data)
# Output: {'name': 'Alice', 'age': 25, 'isStudent': False}
# Access individual elements
print(data["name"]) # Output: Alice
Working with JSON Files
Writing JSON to a File
To save a JSON string to a file, use the json.dump()
method.
# Python object
data = {"name": "Bob", "age": 30, "isStudent": True}
# Write JSON to a file
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
Reading JSON from a File
To read a JSON file and convert it to a Python object, use the json.load()
method.
# Read JSON from a file
with open("data.json", "r") as file:
data = json.load(file)
print(data)
Handling JSON Errors
If the JSON string or file is malformed, Python raises a JSONDecodeError
.
import json
invalid_json = '{"name": "Alice", "age": 25, "isStudent": False'
try:
data = json.loads(invalid_json)
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
Custom Encoding with JSONEncoder
If you have custom Python objects, you can define how they should be serialized using the JSONEncoder
class.
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Custom encoder
class PersonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Person):
return {"name": obj.name, "age": obj.age}
return super().default(obj)
# Convert custom object to JSON
person = Person("Alice", 25)
person_json = json.dumps(person, cls=PersonEncoder)
print(person_json)
# Output: {"name": "Alice", "age": 25}
Using object_hook
for Custom Decoding
You can use the object_hook
parameter to define how JSON objects are decoded into custom Python objects.
import json
# JSON string
json_string = '{"name": "Alice", "age": 25}'
# Custom decoding function
def custom_decoder(obj):
return Person(obj["name"], obj["age"])
# Decode JSON to custom object
person = json.loads(json_string, object_hook=custom_decoder)
print(person.name) # Output: Alice
Comparison of JSON Functions
Function | Description |
---|---|
json.dumps() | Convert Python object to JSON string. |
json.dump() | Write Python object as JSON to a file. |
json.loads() | Parse JSON string to Python object. |
json.load() | Parse JSON file to Python object. |
Use Cases of JSON Module
- API Communication: JSON is the most commonly used format for APIs.
- Configuration Files: Store settings or configurations in a structured way.
- Data Persistence: Save Python data structures to JSON for later use.
- Data Sharing: Share data between different platforms or programming languages.
JSON is an essential part of Python programming, especially in web development, data processing, and APIs.
Read JSON from a URL
from urllib.request import urlopen
# import json
import json
# store the URL in url as
# parameter for urlopen
url = "https://api.github.com"
# store the response of URL
response = urlopen(url)
# storing the JSON response
# from url in data
data_json = json.loads(response.read())
# print the json response
print(data_json)
Example 2
# Import the requests module
import requests
# Send a GET request to the desired API URL
response = requests.get('https://jsonplaceholder.typicode.com/posts')
# Parse the response and print it
data = response.json()
print(data)