agyanadda@gmail.com

Python JSON

Advanced Python 1 min read Updated Dec 4, 2026 Topic 28 of 32

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 → Python
  • json.dumps(obj) — Python → JSON text

Files

  • json.load(f) — read from a file
  • json.dump(obj, f) — write to a file

(The s means string.)

Options

  • indent=2 — pretty output
  • ensure_ascii=False — keep Hindi and other non-English text readable
  • sort_keys=True
  • default=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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which function converts a JSON string into a Python object?

Exercise 2 True / False

JSON null becomes None in Python.

Exercise 3 Fill in the Blank

Pretty-print JSON with json.dumps(obj, ___=2)

Frequently Asked Questions

JSON has no date type. Pass default=str to convert unknown values to text, or convert dates yourself with .isoformat() before saving.