json.dumps(obj) serializes a Python object, dicts, lists, strings, numbers, booleans, None, into a JSON-formatted string, and json.loads(text) does the reverse, parsing JSON text back into Python objects — dicts become dicts, arrays become lists, and so on. The dump/load pair, without the trailing s, work directly with an already-open file object instead of a string, for reading/writing JSON files without manually handling the text yourself. Not every Python object is JSON-serializable by default — custom classes, sets, and datetime objects raise a TypeError unless you provide a custom encoder.
1Understanding json Module
json.dumps(obj) serializes a Python object, dicts, lists, strings, numbers, booleans, None, into a JSON-formatted string, and json.loads(text) does the reverse, parsing JSON text back into Python objects — dicts become dicts, arrays become lists, and so on. The dump/load pair, without the trailing s, work directly with an already-open file object instead of a string, for reading/writing JSON files without manually handling the text yourself. Not every Python object is JSON-serializable by default — custom classes, sets, and datetime objects raise a TypeError unless you provide a custom encoder.
Pass indent=2 (or another number) to json.dumps() when you want human-readable, pretty-printed output, such as writing a config file meant to be edited by hand — the default is a single compact line with no extra whitespace.
import json
data = {"name": "Alice", "age": 30, "active": True}
json_text = json.dumps(data)
print(json_text)2Practical Example
Here is a real-world application of json Module showing how it is used in production Python code.
import json
json_text = '{"items": ["apple", "banana"], "count": 2}'
data = json.loads(json_text)
print(data["items"])
print(type(data))3Best Practices
Follow these guidelines when working with json Module:
1. Use json.dump()/json.load() directly with file objects instead of manually reading/writing text and calling dumps()/loads() separately
2. Pass indent=2 to json.dumps() for human-readable output when the JSON might be read or edited by a person
3. Write a custom default function for json.dumps(), or a custom JSONEncoder, when serializing objects, like dates or custom classes, that aren't JSON-serializable by default
Tip: Pass indent=2 (or another number) to json.dumps() when you want human-readable, pretty-printed output, such as writing a config file meant to be edited by hand — the default is a single compact line with no extra whitespace.
import json
data = {"name": "Alice", "age": 30, "active": True}
json_text = json.dumps(data)
print(json_text)