Python Modules & Packages
Python JSON Handling
The json module converts between Python objects like dictionaries and lists, and JSON text — the universal data format used by web APIs and config files.
Why JSON Matters in Python
JSON, short for JavaScript Object Notation, is the most common way applications exchange data over the internet. Python's built-in json module converts your familiar dictionaries and lists into JSON text, and back again, with almost no extra work.
Converting a Python Object to a JSON String: json.dumps()
json.dumps() takes a Python object, usually a dictionary, and returns it as a JSON-formatted string, ready to send over a network or save to a file.
import json
student = {"name": "Aarav", "age": 21, "passed": True}
json_text = json.dumps(student)
print(json_text)Converting a JSON String Back to Python: json.loads()
json.loads() does the reverse — it parses a JSON string and turns it back into native Python objects like dictionaries, lists, strings, and numbers.
json_text = '{"name": "Aarav", "age": 21}'
data = json.loads(json_text)
print(data["name"])Working With JSON Files: dump() and load()
When your data lives in a .json file instead of a string, use json.dump() to write and json.load() to read, passing an open file object instead of a string.
with open("student.json", "w") as f:
json.dump(student, f)with open("student.json", "r") as f:
data = json.load(f)
print(data)How Python and JSON Types Map to Each Other
JSON has fewer data types than Python, so the json module automatically translates between the closest equivalents in each direction.
| Python Type | JSON Type |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float | number |
| True / False | true / false |
| None | null |
JSON has no tuple type — tuples are converted to JSON arrays, and when you load them back you get a list, not a tuple.
