Python JSON

Parse, serialize, and pretty-print JSON with correct encoding.

  • python json
  • json dumps
  • json loads
  • json.tool
  • ensure_ascii

Python JSON

Parse, serialize, and pretty-print JSON with correct encoding.

Commands

CommandWhat it does
json.loads(text)Parse a JSON string
json.load(open("a.json", encoding="utf-8"))Parse a file
json.dumps(obj, ensure_ascii=False, indent=2)Pretty, unicode-preserving output
json.load with object_hookCustom decoding
python -m json.tool a.jsonCLI pretty-printer

Example

import json
raw = open("a.json", encoding="utf-8").read()
data = json.loads(raw)
print(json.dumps(data, ensure_ascii=False, indent=2)[:200])

FAQ

How do I serialize datetimes/decimals?

Pass default=str, or a custom JSONEncoder; JSON has no native date type.

Why ensure_ascii=False?

Keeps CJK readable in output instead of \uXXXX escapes.

FAQ

How do I serialize datetimes/decimals?
Pass default=str, or a custom JSONEncoder; JSON has no native date type.
Why ensure_ascii=False?
Keeps CJK readable in output instead of \uXXXX escapes.

Python