To convert data handled within a Python program, such as dictionaries (dict) or lists (list), into “JSON formatted strings” for Web API transmission or log output, use the dumps() function from the standard json module.
This article also explains important optional arguments (ensure_ascii, indent) that are crucial when handling non-ASCII data (like Japanese) or when you want human-readable output.
Implementation Example: JSONizing Library Book Data
In this scenario, we convert “Library Collection Information,” managed as a Python dictionary, into a JSON string for transmission to an external system.
Source Code
import json
# 1. Prepare Python dictionary data
# Includes strings, numbers, booleans, and nested lists
library_data = {
"library_name": "Central Library",
"location": "Tokyo",
"books": [
{
"title": "I Am a Cat",
"author": "Natsume Soseki",
"is_available": True
},
{
"title": "Night on the Galactic Railroad",
"author": "Miyazawa Kenji",
"is_available": False
}
],
"total_count": 15000
}
# 2. Convert dictionary to JSON formatted string using json.dumps()
# 'dumps' stands for 'dump string'
# ensure_ascii=False : Output non-ASCII characters directly without Unicode escaping (\uXXXX)
# indent=4 : Format with indentation for readability (Pretty Print)
json_str = json.dumps(library_data, ensure_ascii=False, indent=4)
# Check results
print("--- Converted Type ---")
print(type(json_str)) # <class 'str'>
print("\n--- JSON String ---")
print(json_str)
Execution Result
--- Converted Type ---
<class 'str'>
--- JSON String ---
{
"library_name": "Central Library",
"location": "Tokyo",
"books": [
{
"title": "I Am a Cat",
"author": "Natsume Soseki",
"is_available": true
},
{
"title": "Night on the Galactic Railroad",
"author": "Miyazawa Kenji",
"is_available": false
}
],
"total_count": 15000
}
Explanation
Role of json.dumps(obj)
It takes a Python object and returns a string in JSON format. (Note: This is different from json.dump(), which writes directly to a file).
Important Optional Arguments
ensure_ascii=False
- Default (
True): All non-ASCII characters are converted to Unicode escape sequences (e.g.,\u6771). This is safer for data transfer compatibility but not human-readable. False: Outputs characters as they are. This is essential if you want to display languages like Japanese correctly in logs or on screen.
indent=Number
- No specification: Outputs as a single-line string without newlines or extra spaces (minimized data size).
- Number (e.g., 2 or 4): Indents by the specified number of spaces, formatting the output hierarchically (Pretty Print). This is very useful for debugging or generating configuration files.
Python Type Conversion
- Python
True/Falseconverts to JSONtrue/false(lowercase). - Python
Noneconverts to JSONnull.
