JSON is the most common format for APIs and config files. Python's built-in json module converts between JSON text and Python objects.
Mapping
| JSON | Python |
|---|---|
object {} |
dict |
array [] |
list |
| string | str |
| number | int / float |
true / false |
True / False |
null |
None |
Strings
json.loads(text)— JSON text → Pythonjson.dumps(obj)— Python → JSON text
Files
json.load(f)— read from a filejson.dump(obj, f)— write to a file
(The s means string.)
Options
indent=2— pretty outputensure_ascii=False— keep Hindi and other non-English text readablesort_keys=Truedefault=str— convert values JSON doesn't know (like dates)
Invalid JSON raises json.JSONDecodeError. Remember: JSON needs double quotes and does not allow trailing commas.
Example
Example — Settings file and API data
Python
import json
from datetime import date
api_response = '{"user": {"name": "आशा", "active": true, "skills": ["Python", "SQL"], "phone": null}}'
data = json.loads(api_response)
print(data["user"]["name"], data["user"]["active"], data["user"]["phone"])
settings = {"theme": "dark", "font_size": 14, "updated": date(2026, 12, 3)}
with open("settings.json", "w", encoding="utf-8") as f:
json.dump(settings, f, indent=2, ensure_ascii=False, default=str)
with open("settings.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded)
try:
json.loads("{'bad': 'quotes'}")
except json.JSONDecodeError as e:
print("Invalid JSON:", e.msg)
Output: आशा True None, then {'theme': 'dark', 'font_size': 14, 'updated': '2026-12-03'} (the date was saved as text), then Invalid JSON: Expecting property name enclosed in double quotes.