🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

json Module

AI & DATA SCIENCE // json-module

The json module converts between Python objects and JSON (JavaScript Object Notation) text, the standard format for exchanging structured data over the web.

Syntax

import json
json.dumps(obj)
json.loads(text)
json.dump(obj, file)
json.load(file)

Deep Dive Course

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.

editor.html
import json

data = {"name": "Alice", "age": 30, "active": True}
json_text = json.dumps(data)
print(json_text)
localhost:3000

2Practical Example

Here is a real-world application of json Module showing how it is used in production Python code.

editor.html
import json

json_text = '{"items": ["apple", "banana"], "count": 2}'
data = json.loads(json_text)
print(data["items"])
print(type(data))
localhost:3000

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.

editor.html
import json

data = {"name": "Alice", "age": 30, "active": True}
json_text = json.dumps(data)
print(json_text)
localhost:3000

Examples

Example 01Basic Usage
import json

data = {"name": "Alice", "age": 30, "active": True}
json_text = json.dumps(data)
print(json_text)
Example 02Advanced Example
import json

json_text = '{"items": ["apple", "banana"], "count": 2}'
data = json.loads(json_text)
print(data["items"])
print(type(data))

Best Practices

  • Use json.dump()/json.load() directly with file objects instead of manually reading/writing text and calling dumps()/loads() separately
  • Pass indent=2 to json.dumps() for human-readable output when the JSON might be read or edited by a person
  • 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

Interview Question

Why does json.dumps() raise a TypeError when you try to serialize a Python set or a datetime object?

Hint: Think about what data types JSON's specification actually supports.

The JSON format only defines a small, fixed set of data types: objects, arrays, strings, numbers, booleans, and null. Python's set and datetime have no direct equivalent in that list, so json.dumps() doesn't know how to represent them and raises a TypeError rather than silently guessing an incorrect representation. To serialize such objects, you need to convert them yourself first, for example to a list or an ISO-format string, or supply a custom function that tells json.dumps() how to handle them.

Exercises

MediumPractice using json Module in a real scenario.
View Solution
import json

data = {"name": "Alice", "age": 30, "active": True}
json_text = json.dumps(data)
print(json_text)

Frequently Asked Questions

Why does json.dumps() raise a TypeError when you try to serialize a Python set or a datetime object?

The JSON format only defines a small, fixed set of data types: objects, arrays, strings, numbers, booleans, and null. Python's set and datetime have no direct equivalent in that list, so json.dumps() doesn't know how to represent them and raises a TypeError rather than silently guessing an incorrect representation. To serialize such objects, you need to convert them yourself first, for example to a list or an ISO-format string, or supply a custom function that tells json.dumps() how to handle them.

Related Functions

dictionariesstringswith-statement