|
| 1 | +"""DataChain JSON utilities. |
| 2 | +
|
| 3 | +This module wraps :mod:`ujson` so we can guarantee consistent handling |
| 4 | +of values that the encoder does not support out of the box (for example |
| 5 | +``datetime`` objects or ``bytes``). |
| 6 | +All code inside DataChain should import this module instead of using |
| 7 | +:mod:`ujson` directly. |
| 8 | +""" |
| 9 | + |
| 10 | +import datetime as _dt |
| 11 | +import json as _json |
| 12 | +import uuid as _uuid |
| 13 | +from collections.abc import Callable |
| 14 | +from typing import Any |
| 15 | + |
| 16 | +import ujson as _ujson |
| 17 | + |
| 18 | +__all__ = [ |
| 19 | + "JSONDecodeError", |
| 20 | + "dump", |
| 21 | + "dumps", |
| 22 | + "load", |
| 23 | + "loads", |
| 24 | +] |
| 25 | + |
| 26 | +JSONDecodeError = (_ujson.JSONDecodeError, _json.JSONDecodeError) |
| 27 | + |
| 28 | +_SENTINEL = object() |
| 29 | +_Default = Callable[[Any], Any] |
| 30 | +DEFAULT_PREVIEW_BYTES = 1024 |
| 31 | + |
| 32 | + |
| 33 | +# To make it looks like Pydantic's ISO format with 'Z' for UTC |
| 34 | +# It is minor but nice to have consistency |
| 35 | +def _format_datetime(value: _dt.datetime) -> str: |
| 36 | + iso = value.isoformat() |
| 37 | + |
| 38 | + offset = value.utcoffset() |
| 39 | + if value.tzinfo is None or offset is None: |
| 40 | + return iso |
| 41 | + |
| 42 | + if offset == _dt.timedelta(0) and iso.endswith(("+00:00", "-00:00")): |
| 43 | + return iso[:-6] + "Z" |
| 44 | + |
| 45 | + return iso |
| 46 | + |
| 47 | + |
| 48 | +def _format_time(value: _dt.time) -> str: |
| 49 | + iso = value.isoformat() |
| 50 | + |
| 51 | + offset = value.utcoffset() |
| 52 | + if value.tzinfo is None or offset is None: |
| 53 | + return iso |
| 54 | + |
| 55 | + if offset == _dt.timedelta(0) and iso.endswith(("+00:00", "-00:00")): |
| 56 | + return iso[:-6] + "Z" |
| 57 | + |
| 58 | + return iso |
| 59 | + |
| 60 | + |
| 61 | +def _coerce(value: Any, serialize_bytes: bool) -> Any: |
| 62 | + """Return a JSON-serializable representation for supported extra types.""" |
| 63 | + |
| 64 | + if isinstance(value, _dt.datetime): |
| 65 | + return _format_datetime(value) |
| 66 | + if isinstance(value, _dt.date): |
| 67 | + return value.isoformat() |
| 68 | + if isinstance(value, _dt.time): |
| 69 | + return _format_time(value) |
| 70 | + if isinstance(value, _uuid.UUID): |
| 71 | + return str(value) |
| 72 | + if serialize_bytes and isinstance(value, (bytes, bytearray)): |
| 73 | + return list(bytes(value)[:DEFAULT_PREVIEW_BYTES]) |
| 74 | + return _SENTINEL |
| 75 | + |
| 76 | + |
| 77 | +def _base_default(value: Any, serialize_bytes: bool) -> Any: |
| 78 | + converted = _coerce(value, serialize_bytes) |
| 79 | + if converted is not _SENTINEL: |
| 80 | + return converted |
| 81 | + raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable") |
| 82 | + |
| 83 | + |
| 84 | +def _build_default(user_default: _Default | None, serialize_bytes: bool) -> _Default: |
| 85 | + if user_default is None: |
| 86 | + return lambda value: _base_default(value, serialize_bytes) |
| 87 | + |
| 88 | + def combined(value: Any) -> Any: |
| 89 | + converted = _coerce(value, serialize_bytes) |
| 90 | + if converted is not _SENTINEL: |
| 91 | + return converted |
| 92 | + return user_default(value) |
| 93 | + |
| 94 | + return combined |
| 95 | + |
| 96 | + |
| 97 | +def dumps( |
| 98 | + obj: Any, |
| 99 | + *, |
| 100 | + default: _Default | None = None, |
| 101 | + serialize_bytes: bool = False, |
| 102 | + **kwargs: Any, |
| 103 | +) -> str: |
| 104 | + """Serialize *obj* to a JSON-formatted ``str``.""" |
| 105 | + |
| 106 | + if serialize_bytes: |
| 107 | + return _json.dumps(obj, default=_build_default(default, True), **kwargs) |
| 108 | + |
| 109 | + return _ujson.dumps(obj, default=_build_default(default, False), **kwargs) |
| 110 | + |
| 111 | + |
| 112 | +def dump( |
| 113 | + obj: Any, |
| 114 | + fp, |
| 115 | + *, |
| 116 | + default: _Default | None = None, |
| 117 | + serialize_bytes: bool = False, |
| 118 | + **kwargs: Any, |
| 119 | +) -> None: |
| 120 | + """Serialize *obj* as a JSON formatted stream to *fp*.""" |
| 121 | + |
| 122 | + if serialize_bytes: |
| 123 | + _json.dump(obj, fp, default=_build_default(default, True), **kwargs) |
| 124 | + return |
| 125 | + |
| 126 | + _ujson.dump(obj, fp, default=_build_default(default, False), **kwargs) |
| 127 | + |
| 128 | + |
| 129 | +def loads(s: str | bytes | bytearray, **kwargs: Any) -> Any: |
| 130 | + """Deserialize *s* to a Python object.""" |
| 131 | + |
| 132 | + return _ujson.loads(s, **kwargs) |
| 133 | + |
| 134 | + |
| 135 | +def load(fp, **kwargs: Any) -> Any: |
| 136 | + """Deserialize JSON content from *fp* to a Python object.""" |
| 137 | + |
| 138 | + return loads(fp.read(), **kwargs) |
0 commit comments