Home >Backend Development >Python Tutorial >How Can I Avoid Double Serialization When Returning JSON Data in FastAPI?
When returning JSON data in FastAPI using json.dumps(), avoid double serialization. FastAPI performs automatic serialization behind the scenes, so invoking json.dumps() manually can lead to garbled output, visible as a string instead of JSON.
Option 1: Automatic Serialization
Simply return data as dictionaries, lists, etc. FastAPI will automatically convert it to JSON-compatible format using its built-in jsonable_encoder and wrap it in a JSONResponse. This approach ensures proper serialization and support for serialization of non-serializable objects like datetimes.
from datetime import date data = [{"User": "a", "date": date.today(), "count": 1}] @app.get('/') async def main(): return data
Option 2: Custom Serialization
In specific scenarios, manual serialization may be necessary. In that case, consider returning a custom Response object with the media type set to application/json.
import json @app.get('/') async def main(): json_str = json.dumps(data, indent=4, default=str) return Response(content=json_str, media_type='application/json')
The above is the detailed content of How Can I Avoid Double Serialization When Returning JSON Data in FastAPI?. For more information, please follow other related articles on the PHP Chinese website!