cells-json 0.3.2__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. cells_json-0.4.0/PKG-INFO +290 -0
  2. cells_json-0.4.0/README.md +256 -0
  3. cells_json-0.4.0/cells/json/__init__.py +45 -0
  4. cells_json-0.4.0/cells/json/_dependencies.py +25 -0
  5. cells_json-0.4.0/cells/json/adapter.py +841 -0
  6. cells_json-0.4.0/cells/json/exceptions.py +158 -0
  7. cells_json-0.4.0/cells/json/serializer.py +860 -0
  8. {cells_json-0.3.2 → cells_json-0.4.0}/cells/json/utils.py +35 -35
  9. cells_json-0.4.0/cells/json/version.py +1 -0
  10. cells_json-0.4.0/cells_json.egg-info/PKG-INFO +290 -0
  11. {cells_json-0.3.2 → cells_json-0.4.0}/cells_json.egg-info/SOURCES.txt +2 -0
  12. {cells_json-0.3.2 → cells_json-0.4.0}/setup.py +24 -4
  13. cells_json-0.4.0/tests/test_non_finite.py +715 -0
  14. cells_json-0.4.0/tests/test_performance.py +127 -0
  15. {cells_json-0.3.2 → cells_json-0.4.0}/tests/test_serializer.py +77 -100
  16. cells_json-0.3.2/PKG-INFO +0 -207
  17. cells_json-0.3.2/README.md +0 -188
  18. cells_json-0.3.2/cells/json/__init__.py +0 -44
  19. cells_json-0.3.2/cells/json/adapter.py +0 -548
  20. cells_json-0.3.2/cells/json/exceptions.py +0 -154
  21. cells_json-0.3.2/cells/json/serializer.py +0 -335
  22. cells_json-0.3.2/cells/json/version.py +0 -1
  23. cells_json-0.3.2/cells_json.egg-info/PKG-INFO +0 -207
  24. cells_json-0.3.2/tests/test_performance.py +0 -130
  25. {cells_json-0.3.2 → cells_json-0.4.0}/cells_json.egg-info/dependency_links.txt +0 -0
  26. {cells_json-0.3.2 → cells_json-0.4.0}/cells_json.egg-info/not-zip-safe +0 -0
  27. {cells_json-0.3.2 → cells_json-0.4.0}/cells_json.egg-info/requires.txt +0 -0
  28. {cells_json-0.3.2 → cells_json-0.4.0}/cells_json.egg-info/top_level.txt +0 -0
  29. {cells_json-0.3.2 → cells_json-0.4.0}/setup.cfg +0 -0
@@ -0,0 +1,290 @@
1
+ Metadata-Version: 2.4
2
+ Name: cells-json
3
+ Version: 0.4.0
4
+ Summary: Orjson-first JSON serialization utilities for the cells namespace
5
+ Home-page: https://github.com/pylab-me/cells-json
6
+ Author: HarmonSir
7
+ Author-email: git@pylab.me
8
+ License: MPL-2.0
9
+ Project-URL: Documentation, https://github.com/pylab-me/cells-json#readme
10
+ Project-URL: Issues, https://github.com/pylab-me/cells-json/issues
11
+ Project-URL: Source, https://github.com/pylab-me/cells-json
12
+ Project-URL: Release Notes, https://github.com/pylab-me/cells-json/releases
13
+ Keywords: json,serialization,orjson,deserialization,circular-references,custom-serialization
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ Requires-Dist: orjson
22
+ Dynamic: author
23
+ Dynamic: author-email
24
+ Dynamic: classifier
25
+ Dynamic: description
26
+ Dynamic: description-content-type
27
+ Dynamic: home-page
28
+ Dynamic: keywords
29
+ Dynamic: license
30
+ Dynamic: project-url
31
+ Dynamic: requires-dist
32
+ Dynamic: requires-python
33
+ Dynamic: summary
34
+
35
+ # cells-json
36
+
37
+ [English](README.md) | [简体中文](README-CN.md) | [日本語](README-JP.md)
38
+
39
+ JSON serialization utilities for Python applications, published as `cells-json` and imported as `cells.json`.
40
+
41
+ The library combines an `orjson`-first adapter with a configurable serializer for dates, decimals, identifiers, scientific data, and custom objects. It provides familiar `dump`, `dumps`, `load`, and `loads` entry points, plus recursive conversion when circular references need explicit handling.
42
+
43
+ ## Features
44
+
45
+ - An `orjson`-first adapter with an explicitly selectable standard-library backend.
46
+ - Extended type conversion with cached type handlers.
47
+ - Recursive serialization with circular-reference markers or exceptions.
48
+ - Configurable handling of unknown types and custom objects.
49
+ - Shared encoding and decoding exceptions for the main APIs.
50
+ - File helpers, formatting utilities, and class serialization helpers.
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ python -m pip install cells-json
56
+ ```
57
+
58
+ `orjson` is a required package dependency. NumPy and pandas support is enabled when those packages are installed separately.
59
+
60
+ Requires **Python 3.10 or newer**. CI validates the installed wheel on Linux (3.10 and 3.14) and Windows (3.14).
61
+
62
+ ## Quick start
63
+
64
+ ```python
65
+ from datetime import datetime
66
+ from decimal import Decimal
67
+
68
+ from cells import json
69
+
70
+ payload = json.dumps(
71
+ {"created_at": datetime(2026, 1, 1, 12, 0), "amount": Decimal("19.95")},
72
+ ensure_ascii=False,
73
+ indent=2,
74
+ )
75
+ data = json.loads(payload)
76
+
77
+ assert data["created_at"] == "2026-01-01T12:00:00"
78
+ assert data["amount"] == 19.95
79
+ ```
80
+
81
+ `dumps()` returns `str` by default. With the `orjson` backend, `ensure_str=False` returns `bytes`; the standard-library backend returns `str`. `loads()` accepts `str`, `bytes`, or `bytearray` and returns ordinary Python values.
82
+
83
+ ## Choosing a serialization API
84
+
85
+ | API | Purpose | Encoding path |
86
+ | --- | --- | --- |
87
+ | `dumps()` / `dump()` | Serialize with a familiar standard-library-style interface | Prefers `orjson`; select `backend="json"` explicitly |
88
+ | `loads()` / `load()` | Parse JSON text or a readable stream | Same backend selection as the adapter |
89
+ | `safe_json_dumps()` | Recursively convert an object tree and handle circular references | Standard-library `json` after conversion |
90
+ | `UniversalSerializer` | Reuse type conversion rules or provide a `default` callback | Its `dumps()` and `dump()` use standard-library `json` |
91
+ | `JSONAdapter` | Reuse an adapter with a fixed backend and serializer configuration | Configurable adapter |
92
+
93
+ For recursive conversion:
94
+
95
+ ```python
96
+ from datetime import date
97
+ from cells.json import safe_json_dumps
98
+
99
+ payload = safe_json_dumps(
100
+ {"date": date(2026, 1, 1), "tags": {"python", "json"}},
101
+ ensure_ascii=False,
102
+ indent=2,
103
+ )
104
+ ```
105
+
106
+ `safe_json_dumps()` stringifies dictionary keys and converts tuples and sets to lists before encoding. Set element order is not guaranteed. It does not preserve the original Python types when the JSON is loaded again.
107
+
108
+ ## Backend behavior and compatibility
109
+
110
+ The adapter resembles standard-library `json`, but does not promise identical behavior for every option or value.
111
+
112
+ - `backend="auto"` prefers `orjson` when available and otherwise uses standard-library `json`.
113
+ - `backend="orjson"` requires `orjson`; constructing the adapter without it raises `RuntimeError`.
114
+ - `backend="json"` explicitly selects standard-library encoding and decoding while retaining the library's extended type callback.
115
+
116
+ Automatic backend switching is limited to the documented `allow_nan=True` policy and non-native indentation with `backend="auto"`. Other unsupported options require `backend="json"`. On an orjson-selected adapter, the stdlib fallback preserves `ensure_str=False` and rejects nonzero orjson `option` flags before encoding.
117
+
118
+ | Option | Active `orjson` backend |
119
+ | --- | --- |
120
+ | `ensure_ascii=True` | Supported by escaping non-ASCII characters after encoding; this is the default |
121
+ | `sort_keys=True` | Supported |
122
+ | `indent` | `None` and `2` use orjson; other values use stdlib in `auto` mode. Explicit `backend="orjson"` rejects unsupported indentation unless the `allow_nan=True` fallback applies. |
123
+ | `separators=(",", ":")` | Supported; other explicit separators require `backend="json"` |
124
+ | `skipkeys=True` | Filters unsupported dictionary keys before encoding |
125
+ | `check_circular=False` | Accepted; does not guarantee standard-library circular-reference semantics |
126
+ | `non_finite="null"` (default) | Non-finite values become `null`; non-finite float keys become the string `"null"`. Ambiguous normalized keys raise `JSONEncodeError` |
127
+ | `non_finite="error"` | Supported; raises `JSONEncodeError` naming the path of the first non-finite float |
128
+ | `allow_nan` | Compatibility parameter; `False` selects error, `True` selects stdlib-native encoding, including when orjson is requested. Explicit `non_finite` takes precedence. |
129
+ | Custom encoder/decoder `cls` | Requires `backend="json"` |
130
+ | `object_hook`, `object_pairs_hook`, `parse_float`, `parse_int`, `parse_constant` | Require `backend="json"` |
131
+
132
+ For example, use the standard-library backend to preserve decimal values while parsing:
133
+
134
+ ```python
135
+ from decimal import Decimal
136
+ from cells.json import dumps, loads
137
+
138
+ payload = dumps({"b": 1, "a": 2}, sort_keys=True, indent=2)
139
+ data = loads('{"amount": 19.95}', parse_float=Decimal, backend="json")
140
+
141
+ assert data["amount"] == Decimal("19.95")
142
+ ```
143
+
144
+ The non-finite policy applies to encoding only. `allow_nan=True` selects the stdlib encoder before encoding, even for `backend="orjson"` or `"auto"`. Explicit `non_finite` takes precedence. Nonzero orjson `option` flags cannot be preserved by the fallback and raise `JSONEncodeError`; other stdlib parameters are honored. An orjson-selected adapter preserves bytes when `ensure_str=False`. Decode NaN/Infinity using `backend="json"`; native orjson decoding rejects these non-standard tokens. Decoding retains native backend behavior. The caller's explicit `default` and a custom stdlib encoder's `default()` control unsupported-type conversion. Recursive helpers retain stringified keys and circular markers; non-finite float keys use the encoding policy before stringification. Do not mutate the input graph during encoding; exceptional key normalization needs stable key provenance. Backend-native integer ranges and other dictionary-key behavior can still differ.
145
+
146
+ ## Supported type conversions
147
+
148
+ These conversions describe `UniversalSerializer` and the recursive API. The adapter may use `orjson`'s native support for types that backend already handles.
149
+
150
+ | Python type | JSON representation |
151
+ | --- | --- |
152
+ | `datetime`, `date`, `time` | ISO-formatted string |
153
+ | `timedelta` | Total seconds as a number |
154
+ | `Decimal` | Floating-point number |
155
+ | `UUID` | String |
156
+ | `Enum` | Its `value`, serialized in turn |
157
+ | `Path` | POSIX-style path string |
158
+ | `set`, `tuple` | Array |
159
+ | NumPy `ndarray` / scalar | Nested lists / native Python value |
160
+ | pandas `DataFrame` | Array of row records |
161
+ | Named pandas `Series` | Object mapping its stringified name to a value list |
162
+ | Unnamed pandas `Series` | Index-to-value mapping |
163
+ | Custom object | `to_dict()`, then `__dict__`, then `__slots__`, subject to configuration |
164
+
165
+ `Decimal` conversion to `float` can lose precision. For exact decimal output, provide an explicit conversion such as `default=str` to `dumps()`, or convert values to strings before serialization.
166
+
167
+ ### Custom objects and unknown types
168
+
169
+ ```python
170
+ from cells.json import UniversalSerializer
171
+
172
+
173
+ class User:
174
+ def __init__(self, name):
175
+ self.name = name
176
+
177
+ def to_dict(self):
178
+ return {"name": self.name}
179
+
180
+
181
+ serializer = UniversalSerializer()
182
+ payload = serializer.dumps(User("Alice"))
183
+ ```
184
+
185
+ - `strict=True` disables automatic custom-object inspection, including `to_dict()`. Built-in supported conversions remain available.
186
+ - `ignore_unknown=True` converts otherwise unhandled values to `null` and disables attribute inspection by default. A recognized `to_dict()` method can still be used unless strict mode is enabled.
187
+ - `use_dict=False` disables `__dict__` and `__slots__` inspection while leaving `to_dict()` available outside strict mode.
188
+ - `UniversalSerializer(default=callback)` supplies a fallback for unhandled types.
189
+
190
+ Unknown types raise `JSONEncodeError` when no fallback applies. Automatic attribute inspection can include internal attributes; define `to_dict()` or disable inspection when you need explicit field selection.
191
+
192
+ ## Circular references
193
+
194
+ Use `safe_json_dumps()` for recursive circular-reference handling. The default behavior replaces a cycle with a string such as `"<CircularReference dict>"`; `fail_on_circular=True` raises `CircularReferenceError`.
195
+
196
+ ```python
197
+ from cells.json import CircularReferenceError, safe_json_dumps
198
+
199
+ node = {}
200
+ node["self"] = node
201
+
202
+ payload = safe_json_dumps(node)
203
+ assert "<CircularReference dict>" in payload
204
+
205
+ try:
206
+ safe_json_dumps(node, fail_on_circular=True)
207
+ except CircularReferenceError:
208
+ pass
209
+ ```
210
+
211
+ `UniversalSerializer.dumps()` does not recursively preconvert by default. Use `recursive=True` for that behavior. The adapter APIs do not provide the same recursive marker handling.
212
+
213
+ `safe_json_dumps(ignore_errors=True, default_value="null")` returns the fallback string for serialization exceptions handled by that helper. It does not suppress every possible exception.
214
+
215
+ ## Files and utilities
216
+
217
+ ```python
218
+ from pathlib import Path
219
+ from cells.json import dump, load
220
+ from cells.json.utils import load_json, save_json
221
+
222
+ path = Path("settings.json")
223
+
224
+ with path.open("w", encoding="utf-8") as stream:
225
+ dump({"enabled": True}, stream, indent=2)
226
+
227
+ with path.open("r", encoding="utf-8") as stream:
228
+ data = load(stream)
229
+
230
+ save_json({"enabled": True}, "output/settings.json", indent=2)
231
+ data = load_json("output/settings.json")
232
+ ```
233
+
234
+ The main `dump()` / `load()` APIs operate on open streams. UTF-8 text streams work with both backends. `save_json()` creates parent directories and writes UTF-8 using `UniversalSerializer`; `load_json()` reads UTF-8 using standard-library `json`.
235
+
236
+ Additional helpers:
237
+
238
+ - `prettify_json(data, indent=2)`: serializes a Python value with indentation through `safe_json_dumps()`; also exported from `cells.json`.
239
+ - `JsonSerializable`: base class providing `to_dict()`, `to_json()`, and `from_dict()`.
240
+ - `@json_serializable`: decorator adding the same methods to a class.
241
+
242
+ Import the class helpers from `cells.json.utils`. Their `from_dict()` methods call `cls(**data)`; they do not automatically restore dates, decimals, or other original types.
243
+
244
+ ## Error handling
245
+
246
+ ```python
247
+ from cells.json import JSONDecodeError, JSONEncodeError, dumps, loads
248
+
249
+ try:
250
+ dumps(object(), strict=True)
251
+ except JSONEncodeError as exc:
252
+ print(exc.obj_type, str(exc))
253
+
254
+ try:
255
+ loads("{invalid}")
256
+ except JSONDecodeError as exc:
257
+ print(exc.pos, exc.msg)
258
+ ```
259
+
260
+ `JSONEncodeError` inherits from `TypeError`; `CircularReferenceError` is a subclass of `JSONEncodeError`. `JSONDecodeError` inherits from `ValueError` and exposes `msg`, `doc`, and `pos`. It is not the standard library's `json.JSONDecodeError` class.
261
+
262
+ Unsupported encoding options on the active `orjson` path are reported as `JSONEncodeError`, which is also a `TypeError`. Unsupported decoding options raise `TypeError`. These messages direct callers to `backend="json"`.
263
+
264
+ ## Development and performance
265
+
266
+ From a local checkout, using a supported Python version:
267
+
268
+ ```bash
269
+ python -m pip install -e .
270
+ python -m pip install pytest
271
+ python -m pytest tests/test_serializer.py -v
272
+ ```
273
+
274
+ Tests for NumPy and pandas return early when those optional packages are absent. Install them separately to exercise those conversions.
275
+
276
+ Run the included benchmark with:
277
+
278
+ ```bash
279
+ python tests/test_performance.py
280
+ ```
281
+
282
+ Use `python tests/test_performance.py --markdown benchmark.md` to write a report. The benchmark compares standard-library `json` with the two `cells-json` adapter modes, using equivalent conversions and string output, and reports the median of five repeats.
283
+
284
+ Pushes to `v*` tags publish a GitHub Release with the build archive and benchmark results in its notes. Pushes to `main` update the `rolling` prerelease and its tag to the built commit. GitHub releases created with `GITHUB_TOKEN` do not trigger the separate release-event PyPI workflow.
285
+
286
+ Performance depends on the payload, backend, conversion path, options, and environment. The benchmark is a local comparison tool; no fixed speedup is guaranteed.
287
+
288
+ ## License
289
+
290
+ The package metadata declares the Mozilla Public License 2.0 (`MPL-2.0`).
@@ -0,0 +1,256 @@
1
+ # cells-json
2
+
3
+ [English](README.md) | [简体中文](README-CN.md) | [日本語](README-JP.md)
4
+
5
+ JSON serialization utilities for Python applications, published as `cells-json` and imported as `cells.json`.
6
+
7
+ The library combines an `orjson`-first adapter with a configurable serializer for dates, decimals, identifiers, scientific data, and custom objects. It provides familiar `dump`, `dumps`, `load`, and `loads` entry points, plus recursive conversion when circular references need explicit handling.
8
+
9
+ ## Features
10
+
11
+ - An `orjson`-first adapter with an explicitly selectable standard-library backend.
12
+ - Extended type conversion with cached type handlers.
13
+ - Recursive serialization with circular-reference markers or exceptions.
14
+ - Configurable handling of unknown types and custom objects.
15
+ - Shared encoding and decoding exceptions for the main APIs.
16
+ - File helpers, formatting utilities, and class serialization helpers.
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ python -m pip install cells-json
22
+ ```
23
+
24
+ `orjson` is a required package dependency. NumPy and pandas support is enabled when those packages are installed separately.
25
+
26
+ Requires **Python 3.10 or newer**. CI validates the installed wheel on Linux (3.10 and 3.14) and Windows (3.14).
27
+
28
+ ## Quick start
29
+
30
+ ```python
31
+ from datetime import datetime
32
+ from decimal import Decimal
33
+
34
+ from cells import json
35
+
36
+ payload = json.dumps(
37
+ {"created_at": datetime(2026, 1, 1, 12, 0), "amount": Decimal("19.95")},
38
+ ensure_ascii=False,
39
+ indent=2,
40
+ )
41
+ data = json.loads(payload)
42
+
43
+ assert data["created_at"] == "2026-01-01T12:00:00"
44
+ assert data["amount"] == 19.95
45
+ ```
46
+
47
+ `dumps()` returns `str` by default. With the `orjson` backend, `ensure_str=False` returns `bytes`; the standard-library backend returns `str`. `loads()` accepts `str`, `bytes`, or `bytearray` and returns ordinary Python values.
48
+
49
+ ## Choosing a serialization API
50
+
51
+ | API | Purpose | Encoding path |
52
+ | --- | --- | --- |
53
+ | `dumps()` / `dump()` | Serialize with a familiar standard-library-style interface | Prefers `orjson`; select `backend="json"` explicitly |
54
+ | `loads()` / `load()` | Parse JSON text or a readable stream | Same backend selection as the adapter |
55
+ | `safe_json_dumps()` | Recursively convert an object tree and handle circular references | Standard-library `json` after conversion |
56
+ | `UniversalSerializer` | Reuse type conversion rules or provide a `default` callback | Its `dumps()` and `dump()` use standard-library `json` |
57
+ | `JSONAdapter` | Reuse an adapter with a fixed backend and serializer configuration | Configurable adapter |
58
+
59
+ For recursive conversion:
60
+
61
+ ```python
62
+ from datetime import date
63
+ from cells.json import safe_json_dumps
64
+
65
+ payload = safe_json_dumps(
66
+ {"date": date(2026, 1, 1), "tags": {"python", "json"}},
67
+ ensure_ascii=False,
68
+ indent=2,
69
+ )
70
+ ```
71
+
72
+ `safe_json_dumps()` stringifies dictionary keys and converts tuples and sets to lists before encoding. Set element order is not guaranteed. It does not preserve the original Python types when the JSON is loaded again.
73
+
74
+ ## Backend behavior and compatibility
75
+
76
+ The adapter resembles standard-library `json`, but does not promise identical behavior for every option or value.
77
+
78
+ - `backend="auto"` prefers `orjson` when available and otherwise uses standard-library `json`.
79
+ - `backend="orjson"` requires `orjson`; constructing the adapter without it raises `RuntimeError`.
80
+ - `backend="json"` explicitly selects standard-library encoding and decoding while retaining the library's extended type callback.
81
+
82
+ Automatic backend switching is limited to the documented `allow_nan=True` policy and non-native indentation with `backend="auto"`. Other unsupported options require `backend="json"`. On an orjson-selected adapter, the stdlib fallback preserves `ensure_str=False` and rejects nonzero orjson `option` flags before encoding.
83
+
84
+ | Option | Active `orjson` backend |
85
+ | --- | --- |
86
+ | `ensure_ascii=True` | Supported by escaping non-ASCII characters after encoding; this is the default |
87
+ | `sort_keys=True` | Supported |
88
+ | `indent` | `None` and `2` use orjson; other values use stdlib in `auto` mode. Explicit `backend="orjson"` rejects unsupported indentation unless the `allow_nan=True` fallback applies. |
89
+ | `separators=(",", ":")` | Supported; other explicit separators require `backend="json"` |
90
+ | `skipkeys=True` | Filters unsupported dictionary keys before encoding |
91
+ | `check_circular=False` | Accepted; does not guarantee standard-library circular-reference semantics |
92
+ | `non_finite="null"` (default) | Non-finite values become `null`; non-finite float keys become the string `"null"`. Ambiguous normalized keys raise `JSONEncodeError` |
93
+ | `non_finite="error"` | Supported; raises `JSONEncodeError` naming the path of the first non-finite float |
94
+ | `allow_nan` | Compatibility parameter; `False` selects error, `True` selects stdlib-native encoding, including when orjson is requested. Explicit `non_finite` takes precedence. |
95
+ | Custom encoder/decoder `cls` | Requires `backend="json"` |
96
+ | `object_hook`, `object_pairs_hook`, `parse_float`, `parse_int`, `parse_constant` | Require `backend="json"` |
97
+
98
+ For example, use the standard-library backend to preserve decimal values while parsing:
99
+
100
+ ```python
101
+ from decimal import Decimal
102
+ from cells.json import dumps, loads
103
+
104
+ payload = dumps({"b": 1, "a": 2}, sort_keys=True, indent=2)
105
+ data = loads('{"amount": 19.95}', parse_float=Decimal, backend="json")
106
+
107
+ assert data["amount"] == Decimal("19.95")
108
+ ```
109
+
110
+ The non-finite policy applies to encoding only. `allow_nan=True` selects the stdlib encoder before encoding, even for `backend="orjson"` or `"auto"`. Explicit `non_finite` takes precedence. Nonzero orjson `option` flags cannot be preserved by the fallback and raise `JSONEncodeError`; other stdlib parameters are honored. An orjson-selected adapter preserves bytes when `ensure_str=False`. Decode NaN/Infinity using `backend="json"`; native orjson decoding rejects these non-standard tokens. Decoding retains native backend behavior. The caller's explicit `default` and a custom stdlib encoder's `default()` control unsupported-type conversion. Recursive helpers retain stringified keys and circular markers; non-finite float keys use the encoding policy before stringification. Do not mutate the input graph during encoding; exceptional key normalization needs stable key provenance. Backend-native integer ranges and other dictionary-key behavior can still differ.
111
+
112
+ ## Supported type conversions
113
+
114
+ These conversions describe `UniversalSerializer` and the recursive API. The adapter may use `orjson`'s native support for types that backend already handles.
115
+
116
+ | Python type | JSON representation |
117
+ | --- | --- |
118
+ | `datetime`, `date`, `time` | ISO-formatted string |
119
+ | `timedelta` | Total seconds as a number |
120
+ | `Decimal` | Floating-point number |
121
+ | `UUID` | String |
122
+ | `Enum` | Its `value`, serialized in turn |
123
+ | `Path` | POSIX-style path string |
124
+ | `set`, `tuple` | Array |
125
+ | NumPy `ndarray` / scalar | Nested lists / native Python value |
126
+ | pandas `DataFrame` | Array of row records |
127
+ | Named pandas `Series` | Object mapping its stringified name to a value list |
128
+ | Unnamed pandas `Series` | Index-to-value mapping |
129
+ | Custom object | `to_dict()`, then `__dict__`, then `__slots__`, subject to configuration |
130
+
131
+ `Decimal` conversion to `float` can lose precision. For exact decimal output, provide an explicit conversion such as `default=str` to `dumps()`, or convert values to strings before serialization.
132
+
133
+ ### Custom objects and unknown types
134
+
135
+ ```python
136
+ from cells.json import UniversalSerializer
137
+
138
+
139
+ class User:
140
+ def __init__(self, name):
141
+ self.name = name
142
+
143
+ def to_dict(self):
144
+ return {"name": self.name}
145
+
146
+
147
+ serializer = UniversalSerializer()
148
+ payload = serializer.dumps(User("Alice"))
149
+ ```
150
+
151
+ - `strict=True` disables automatic custom-object inspection, including `to_dict()`. Built-in supported conversions remain available.
152
+ - `ignore_unknown=True` converts otherwise unhandled values to `null` and disables attribute inspection by default. A recognized `to_dict()` method can still be used unless strict mode is enabled.
153
+ - `use_dict=False` disables `__dict__` and `__slots__` inspection while leaving `to_dict()` available outside strict mode.
154
+ - `UniversalSerializer(default=callback)` supplies a fallback for unhandled types.
155
+
156
+ Unknown types raise `JSONEncodeError` when no fallback applies. Automatic attribute inspection can include internal attributes; define `to_dict()` or disable inspection when you need explicit field selection.
157
+
158
+ ## Circular references
159
+
160
+ Use `safe_json_dumps()` for recursive circular-reference handling. The default behavior replaces a cycle with a string such as `"<CircularReference dict>"`; `fail_on_circular=True` raises `CircularReferenceError`.
161
+
162
+ ```python
163
+ from cells.json import CircularReferenceError, safe_json_dumps
164
+
165
+ node = {}
166
+ node["self"] = node
167
+
168
+ payload = safe_json_dumps(node)
169
+ assert "<CircularReference dict>" in payload
170
+
171
+ try:
172
+ safe_json_dumps(node, fail_on_circular=True)
173
+ except CircularReferenceError:
174
+ pass
175
+ ```
176
+
177
+ `UniversalSerializer.dumps()` does not recursively preconvert by default. Use `recursive=True` for that behavior. The adapter APIs do not provide the same recursive marker handling.
178
+
179
+ `safe_json_dumps(ignore_errors=True, default_value="null")` returns the fallback string for serialization exceptions handled by that helper. It does not suppress every possible exception.
180
+
181
+ ## Files and utilities
182
+
183
+ ```python
184
+ from pathlib import Path
185
+ from cells.json import dump, load
186
+ from cells.json.utils import load_json, save_json
187
+
188
+ path = Path("settings.json")
189
+
190
+ with path.open("w", encoding="utf-8") as stream:
191
+ dump({"enabled": True}, stream, indent=2)
192
+
193
+ with path.open("r", encoding="utf-8") as stream:
194
+ data = load(stream)
195
+
196
+ save_json({"enabled": True}, "output/settings.json", indent=2)
197
+ data = load_json("output/settings.json")
198
+ ```
199
+
200
+ The main `dump()` / `load()` APIs operate on open streams. UTF-8 text streams work with both backends. `save_json()` creates parent directories and writes UTF-8 using `UniversalSerializer`; `load_json()` reads UTF-8 using standard-library `json`.
201
+
202
+ Additional helpers:
203
+
204
+ - `prettify_json(data, indent=2)`: serializes a Python value with indentation through `safe_json_dumps()`; also exported from `cells.json`.
205
+ - `JsonSerializable`: base class providing `to_dict()`, `to_json()`, and `from_dict()`.
206
+ - `@json_serializable`: decorator adding the same methods to a class.
207
+
208
+ Import the class helpers from `cells.json.utils`. Their `from_dict()` methods call `cls(**data)`; they do not automatically restore dates, decimals, or other original types.
209
+
210
+ ## Error handling
211
+
212
+ ```python
213
+ from cells.json import JSONDecodeError, JSONEncodeError, dumps, loads
214
+
215
+ try:
216
+ dumps(object(), strict=True)
217
+ except JSONEncodeError as exc:
218
+ print(exc.obj_type, str(exc))
219
+
220
+ try:
221
+ loads("{invalid}")
222
+ except JSONDecodeError as exc:
223
+ print(exc.pos, exc.msg)
224
+ ```
225
+
226
+ `JSONEncodeError` inherits from `TypeError`; `CircularReferenceError` is a subclass of `JSONEncodeError`. `JSONDecodeError` inherits from `ValueError` and exposes `msg`, `doc`, and `pos`. It is not the standard library's `json.JSONDecodeError` class.
227
+
228
+ Unsupported encoding options on the active `orjson` path are reported as `JSONEncodeError`, which is also a `TypeError`. Unsupported decoding options raise `TypeError`. These messages direct callers to `backend="json"`.
229
+
230
+ ## Development and performance
231
+
232
+ From a local checkout, using a supported Python version:
233
+
234
+ ```bash
235
+ python -m pip install -e .
236
+ python -m pip install pytest
237
+ python -m pytest tests/test_serializer.py -v
238
+ ```
239
+
240
+ Tests for NumPy and pandas return early when those optional packages are absent. Install them separately to exercise those conversions.
241
+
242
+ Run the included benchmark with:
243
+
244
+ ```bash
245
+ python tests/test_performance.py
246
+ ```
247
+
248
+ Use `python tests/test_performance.py --markdown benchmark.md` to write a report. The benchmark compares standard-library `json` with the two `cells-json` adapter modes, using equivalent conversions and string output, and reports the median of five repeats.
249
+
250
+ Pushes to `v*` tags publish a GitHub Release with the build archive and benchmark results in its notes. Pushes to `main` update the `rolling` prerelease and its tag to the built commit. GitHub releases created with `GITHUB_TOKEN` do not trigger the separate release-event PyPI workflow.
251
+
252
+ Performance depends on the payload, backend, conversion path, options, and environment. The benchmark is a local comparison tool; no fixed speedup is guaranteed.
253
+
254
+ ## License
255
+
256
+ The package metadata declares the Mozilla Public License 2.0 (`MPL-2.0`).
@@ -0,0 +1,45 @@
1
+ """JSON serialization utilities / JSON 序列化工具模块
2
+
3
+ Provide general JSON serialization for common Python serialization needs: / 提供通用的 JSON 序列化能力,处理 Python 中常见的序列化问题:
4
+ - Serialize datetime/date objects / datetime/date 对象序列化
5
+ - Serialize Decimal objects / Decimal 对象序列化
6
+ - Serialize UUID objects / UUID 对象序列化
7
+ - Serialize NumPy arrays / numpy 数组序列化
8
+ - Serialize custom objects / 自定义对象的序列化
9
+ - Serialize complex data structures / 复杂数据结构的序列化
10
+ - Support multiple JSON backends (json, orjson) / 多种 JSON 后端支持(json、orjson)
11
+ """
12
+
13
+ from .adapter import JSONAdapter, dump, dumps, load, loads
14
+ from .exceptions import (
15
+ CircularReferenceError,
16
+ JSONDecodeError,
17
+ JSONEncodeError,
18
+ JSONSerializationError,
19
+ UnsupportedTypeError,
20
+ )
21
+ from .serializer import NonFinitePolicy, UniversalSerializer, safe_json_dumps
22
+ from .utils import prettify_json
23
+ from .version import __VERSION__
24
+
25
+
26
+ __all__ = [
27
+ # Core serializers / 核心序列化器
28
+ "UniversalSerializer",
29
+ "NonFinitePolicy",
30
+ "safe_json_dumps",
31
+ # Exception classes / 异常类
32
+ "JSONSerializationError",
33
+ "JSONEncodeError",
34
+ "JSONDecodeError",
35
+ "CircularReferenceError",
36
+ "UnsupportedTypeError",
37
+ # Adapter (supports multiple JSON backends) / 适配器(支持多种 JSON 后端)
38
+ "JSONAdapter",
39
+ "dump",
40
+ "dumps",
41
+ "load",
42
+ "loads",
43
+ "prettify_json",
44
+ "__VERSION__",
45
+ ]
@@ -0,0 +1,25 @@
1
+ """Third-party dependency availability / 第三方依赖可用性检测。"""
2
+
3
+ try:
4
+ import numpy as np
5
+
6
+ HAS_NUMPY = True
7
+ except ImportError:
8
+ np = None
9
+ HAS_NUMPY = False
10
+
11
+ try:
12
+ import pandas as pd
13
+
14
+ HAS_PANDAS = True
15
+ except ImportError:
16
+ pd = None
17
+ HAS_PANDAS = False
18
+
19
+ try:
20
+ import orjson
21
+
22
+ HAS_ORJSON = True
23
+ except ImportError:
24
+ orjson = None
25
+ HAS_ORJSON = False