How do you read and write JSON in Python?
Use the json module: json.dumps and json.loads convert between Python objects and JSON strings, while json.dump and json.load do the same with file objects. JSON null becomes None, and keys always become strings.
Explain it simply
JSON is a plain-text way to carry data between programs, like writing an address on a postcard so that anyone can read it. dumps ("dump to string") writes the postcard; loads ("load from string") reads it back into Python objects. The versions without the s work directly on files.
Example
import json
student = {"name": "Asha", "marks": [80, 92], "passed": True, "mentor": None}
text = json.dumps(student)
print(text) # Output: {"name": "Asha", "marks": [80, 92], "passed": true, "mentor": null}
back = json.loads(text)
print(back["marks"][1]) # Output: 92
with open("student.json", "w", encoding="utf-8") as f:
json.dump(student, f, indent=2)
with open("student.json", encoding="utf-8") as f:
data = json.load(f)
print(data == student) # Output: True
print(json.dumps({1: "a"})) # Output: {"1": "a"}Tuples become arrays and come back as lists. Sets, datetimes and custom classes are not serialisable by default; convert them first or pass a default= function.
What to say in the interview
"dumps and loads work with strings, dump and load with files. Python dict, list, str, int, float, bool and None map to object, array, string, number, true/false and null. Non-string keys turn into strings, and unsupported types need a custom default function or conversion."