1. Introduction
JSON (JavaScript Object Notation) is a lightweight, text-based data format widely used for configuration files, APIs, and data exchange between systems. Python's built-in json module makes it easy to convert between Python objects (dicts, lists, strings, numbers) and JSON text.
Cricket analogy: A cricket board's match-day team sheet, a simple text list of players and roles shared between the scorer and broadcaster, is like JSON -- Python's json module translates it into dicts and lists the program can use.
JSON objects map naturally to Python dictionaries, and JSON arrays map to Python lists, which is why the json module feels so seamless to use with typical Python data structures.
Cricket analogy: A scorecard's key-value pairs like 'batsman: Rohit Sharma, runs: 45' map naturally to a Python dict, while the list of all deliveries in an over maps naturally to a Python list -- just like JSON objects and arrays.
2. Syntax
import json
# Python object <-> JSON string
json_string = json.dumps(python_obj) # serialize to string
python_obj = json.loads(json_string) # parse from string
# Python object <-> JSON file
json.dump(python_obj, file_object) # serialize to a file
python_obj = json.load(file_object) # parse from a file
# Pretty-printing
json.dumps(python_obj, indent=2)3. Explanation
The json module has four core functions that are easy to mix up: dumps() (dump string) converts a Python object into a JSON-formatted string, while loads() (load string) parses a JSON string back into a Python object. dump() and load() do the same conversions but read from or write directly to an open file object instead of working with strings.
Cricket analogy: dumps() is like a commentator converting live match action into a radio broadcast script (string), loads() decodes that script back into the action; dump()/load() do the same but writing straight to a recorded broadcast tape (file).
The 'indent' parameter controls pretty-printing: without it, json.dumps() produces compact output on one line; with indent=2, it produces nicely formatted, human-readable output with 2-space indentation.
Cricket analogy: Without indent, a scorecard is a dense one-line text dump; with indent=2, it's formatted like a neatly aligned printed scorecard in the newspaper, easy for a fan to read at a glance.
It is easy to confuse the 's' functions with the file functions: dumps()/loads() operate on strings, while dump()/load() operate on file objects. Calling json.dump() when you meant json.dumps() (or vice versa) is a common source of bugs.
4. Example
import json, tempfile, os
data = {'name': 'Alice', 'age': 30, 'skills': ['Python', 'SQL']}
json_string = json.dumps(data, indent=2)
print(json_string)
parsed = json.loads(json_string)
print(parsed['name'], parsed['age'])
path = os.path.join(tempfile.gettempdir(), 'demo_data.json')
with open(path, 'w') as f:
json.dump(data, f)
with open(path, 'r') as f:
loaded = json.load(f)
print(loaded == data)
os.remove(path)5. Output
{
"name": "Alice",
"age": 30,
"skills": [
"Python",
"SQL"
]
}
Alice 30
True6. Key Takeaways
- json.dumps()/json.loads() convert between Python objects and JSON strings.
- json.dump()/json.load() convert between Python objects and JSON directly via file objects.
- The 'indent' parameter of dumps()/dump() enables human-readable, pretty-printed output.
- JSON objects map to Python dicts and JSON arrays map to Python lists.
- Mixing up the string functions and file functions is a common source of bugs.
Practice what you learned
1. Which function converts a Python dictionary into a JSON-formatted string?
2. Which function reads JSON data directly from an open file object into a Python object?
3. What Python type does a JSON array become after json.loads()?
4. What does passing indent=2 to json.dumps() do?
5. Which pair of functions operates on file objects rather than strings?
Was this page helpful?
You May Also Like
File Handling in Python
Understand how to open, read, write, and close files in Python using the built-in open() function and file modes.
Reading and Writing Files in Python
Explore the different methods for reading and writing file content, including read(), readline(), readlines(), write(), and writelines().
with Statement (Context Managers) in Python
Learn how the 'with' statement uses the context manager protocol (__enter__/__exit__) to guarantee cleanup, such as automatically closing files.
Dictionaries in Python
Python's key-value mapping type, covering hashable keys, insertion order guarantees (3.7+), common dict methods, and typical gotchas.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics