From String
import json
text = '{"name": "Ming", "age": 17}'
data = json.loads(text) # string โ dict
back = json.dumps(data) # dict โ string
From File
with open("config.json") as f:
data = json.load(f)
with open("config.json", "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
Pretty Printing
print(json.dumps(data, indent=2, sort_keys=True))
Gotchas
- JSON keys are always strings. Python dict keys become strings when dumped.
- JSON has no tuples โ they become lists when loaded.
- Use
ensure_ascii=Falseto keep Chinese characters readable.
Custom Objects
class User:
def __init__(self, name): self.name = name
u = User("Ming")
json.dumps(u.__dict__) # {"name": "Ming"}
Practise this on PyForm โ free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm โ