Converting Python to JSON
2 min read ·
To convert a Python object into JSON string, use
json.dumps().Note
After conversion, the result becomes a string in JSON format.
Converting Different Python Data Types
Python supports conversion of multiple data types into JSON.
Python to JSON Type Mapping
- dictionary becomes object
- list becomes array
- tuple becomes array
- string becomes string
- integer becomes number
- float becomes number
- True becomes true
- False becomes false
- None becomes null
Complex Object Conversion
Formatting JSON Output using indent
To make JSON readable, use
indent.Custom Separators
You can customize how data is separated.
Pro Tip
Use indent when displaying JSON in logs, APIs, or debugging for better readability.
Real World Usage
JSON is widely used in:
- APIs for sending and receiving data
- Configuration files
- Data storage and exchange
Caution
Make sure Python objects are serializable before converting to JSON, otherwise it may raise an error.
Exercise
- Convert a Python dictionary into JSON
- Convert a list into JSON
- Format JSON using indent
- Create a complex object and convert it into JSON