json.py 767 B

12345678910111213141516171819
  1. from collections.abc import Mapping, Sequence
  2. def normalize_json(obj):
  3. """Recursively normalize an object into JSON-compatible types."""
  4. match obj:
  5. case Mapping():
  6. return {normalize_json(k): normalize_json(v) for k, v in obj.items()}
  7. case bytes():
  8. try:
  9. return obj.decode("utf-8")
  10. except UnicodeDecodeError:
  11. raise ValueError(f"Unsupported value: {type(obj)}")
  12. case str() | int() | float() | bool() | None:
  13. return obj
  14. case Sequence(): # str and bytes were already handled.
  15. return [normalize_json(v) for v in obj]
  16. case _: # Other types can't be serialized to JSON
  17. raise TypeError(f"Unsupported type: {type(obj)}")