cells-json 0.3.2__tar.gz → 0.3.3__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.
- cells_json-0.3.3/PKG-INFO +273 -0
- cells_json-0.3.3/README.md +254 -0
- cells_json-0.3.3/cells/json/__init__.py +44 -0
- {cells_json-0.3.2 → cells_json-0.3.3}/cells/json/adapter.py +23 -11
- cells_json-0.3.3/cells/json/exceptions.py +158 -0
- cells_json-0.3.3/cells/json/serializer.py +335 -0
- {cells_json-0.3.2 → cells_json-0.3.3}/cells/json/utils.py +33 -35
- cells_json-0.3.3/cells/json/version.py +1 -0
- cells_json-0.3.3/cells_json.egg-info/PKG-INFO +273 -0
- {cells_json-0.3.2 → cells_json-0.3.3}/setup.py +2 -4
- cells_json-0.3.3/tests/test_performance.py +127 -0
- {cells_json-0.3.2 → cells_json-0.3.3}/tests/test_serializer.py +77 -100
- cells_json-0.3.2/PKG-INFO +0 -207
- cells_json-0.3.2/README.md +0 -188
- cells_json-0.3.2/cells/json/__init__.py +0 -44
- cells_json-0.3.2/cells/json/exceptions.py +0 -154
- cells_json-0.3.2/cells/json/serializer.py +0 -335
- cells_json-0.3.2/cells/json/version.py +0 -1
- cells_json-0.3.2/cells_json.egg-info/PKG-INFO +0 -207
- cells_json-0.3.2/tests/test_performance.py +0 -130
- {cells_json-0.3.2 → cells_json-0.3.3}/cells_json.egg-info/SOURCES.txt +0 -0
- {cells_json-0.3.2 → cells_json-0.3.3}/cells_json.egg-info/dependency_links.txt +0 -0
- {cells_json-0.3.2 → cells_json-0.3.3}/cells_json.egg-info/not-zip-safe +0 -0
- {cells_json-0.3.2 → cells_json-0.3.3}/cells_json.egg-info/requires.txt +0 -0
- {cells_json-0.3.2 → cells_json-0.3.3}/cells_json.egg-info/top_level.txt +0 -0
- {cells_json-0.3.2 → cells_json-0.3.3}/setup.cfg +0 -0
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cells-json
|
|
3
|
+
Version: 0.3.3
|
|
4
|
+
Summary: Orjson-first JSON serialization utilities for the cells namespace
|
|
5
|
+
Author: HarmonSir
|
|
6
|
+
Author-email: git@pylab.me
|
|
7
|
+
License: MPL-2.0
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
Requires-Dist: orjson
|
|
11
|
+
Dynamic: author
|
|
12
|
+
Dynamic: author-email
|
|
13
|
+
Dynamic: description
|
|
14
|
+
Dynamic: description-content-type
|
|
15
|
+
Dynamic: license
|
|
16
|
+
Dynamic: requires-dist
|
|
17
|
+
Dynamic: requires-python
|
|
18
|
+
Dynamic: summary
|
|
19
|
+
|
|
20
|
+
# cells-json
|
|
21
|
+
|
|
22
|
+
[English](README.md) | [简体中文](README-CN.md) | [日本語](README-JP.md)
|
|
23
|
+
|
|
24
|
+
JSON serialization utilities for Python applications, published as `cells-json` and imported as `cells.json`.
|
|
25
|
+
|
|
26
|
+
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.
|
|
27
|
+
|
|
28
|
+
## Features
|
|
29
|
+
|
|
30
|
+
- An `orjson`-first adapter with an explicitly selectable standard-library backend.
|
|
31
|
+
- Extended type conversion with cached type handlers.
|
|
32
|
+
- Recursive serialization with circular-reference markers or exceptions.
|
|
33
|
+
- Configurable handling of unknown types and custom objects.
|
|
34
|
+
- Shared encoding and decoding exceptions for the main APIs.
|
|
35
|
+
- File helpers, formatting utilities, and class serialization helpers.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
python -m pip install cells-json
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`orjson` is a required package dependency. NumPy and pandas support is enabled when those packages are installed separately.
|
|
44
|
+
|
|
45
|
+
Use **Python 3.14** for the current source tree: it uses exception syntax introduced in Python 3.14. Package metadata currently declares `Python >=3.9`; that declaration does not reflect the syntax requirement of the current source. The CI test job is configured for Python 3.14 on Linux and Windows.
|
|
46
|
+
|
|
47
|
+
## Quick start
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from datetime import datetime
|
|
51
|
+
from decimal import Decimal
|
|
52
|
+
|
|
53
|
+
from cells import json
|
|
54
|
+
|
|
55
|
+
payload = json.dumps(
|
|
56
|
+
{"created_at": datetime(2026, 1, 1, 12, 0), "amount": Decimal("19.95")},
|
|
57
|
+
ensure_ascii=False,
|
|
58
|
+
indent=2,
|
|
59
|
+
)
|
|
60
|
+
data = json.loads(payload)
|
|
61
|
+
|
|
62
|
+
assert data["created_at"] == "2026-01-01T12:00:00"
|
|
63
|
+
assert data["amount"] == 19.95
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`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.
|
|
67
|
+
|
|
68
|
+
## Choosing a serialization API
|
|
69
|
+
|
|
70
|
+
| API | Purpose | Encoding path |
|
|
71
|
+
| --- | --- | --- |
|
|
72
|
+
| `dumps()` / `dump()` | Serialize with a familiar standard-library-style interface | Prefers `orjson`; select `backend="json"` explicitly |
|
|
73
|
+
| `loads()` / `load()` | Parse JSON text or a readable stream | Same backend selection as the adapter |
|
|
74
|
+
| `safe_json_dumps()` | Recursively convert an object tree and handle circular references | Standard-library `json` after conversion |
|
|
75
|
+
| `UniversalSerializer` | Reuse type conversion rules or provide a `default` callback | Its `dumps()` and `dump()` use standard-library `json` |
|
|
76
|
+
| `JSONAdapter` | Reuse an adapter with a fixed backend and serializer configuration | Configurable adapter |
|
|
77
|
+
|
|
78
|
+
For recursive conversion:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from datetime import date
|
|
82
|
+
from cells.json import safe_json_dumps
|
|
83
|
+
|
|
84
|
+
payload = safe_json_dumps(
|
|
85
|
+
{"date": date(2026, 1, 1), "tags": {"python", "json"}},
|
|
86
|
+
ensure_ascii=False,
|
|
87
|
+
indent=2,
|
|
88
|
+
)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`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.
|
|
92
|
+
|
|
93
|
+
## Backend behavior and compatibility
|
|
94
|
+
|
|
95
|
+
The adapter resembles standard-library `json`, but does not promise identical behavior for every option or value.
|
|
96
|
+
|
|
97
|
+
- `backend="auto"` prefers `orjson` when available and otherwise uses standard-library `json`.
|
|
98
|
+
- `backend="orjson"` requires `orjson`; constructing the adapter without it raises `RuntimeError`.
|
|
99
|
+
- `backend="json"` explicitly selects standard-library encoding and decoding while retaining the library's extended type callback.
|
|
100
|
+
|
|
101
|
+
Unsupported options do not trigger an automatic backend switch. Select `backend="json"` when standard-library parameter semantics are required.
|
|
102
|
+
|
|
103
|
+
| Option | Active `orjson` backend |
|
|
104
|
+
| --- | --- |
|
|
105
|
+
| `ensure_ascii=True` | Supported by escaping non-ASCII characters after encoding; this is the default |
|
|
106
|
+
| `sort_keys=True` | Supported |
|
|
107
|
+
| `indent=2` | Supported; other non-`None` indentation values require `backend="json"` |
|
|
108
|
+
| `separators=(",", ":")` | Supported; other explicit separators require `backend="json"` |
|
|
109
|
+
| `skipkeys=True` | Filters unsupported dictionary keys before encoding |
|
|
110
|
+
| `check_circular=False` | Accepted; does not guarantee standard-library circular-reference semantics |
|
|
111
|
+
| `allow_nan=False` | Requires `backend="json"` |
|
|
112
|
+
| Custom encoder/decoder `cls` | Requires `backend="json"` |
|
|
113
|
+
| `object_hook`, `object_pairs_hook`, `parse_float`, `parse_int`, `parse_constant` | Require `backend="json"` |
|
|
114
|
+
|
|
115
|
+
For example, use the standard-library backend to preserve decimal values while parsing:
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
from decimal import Decimal
|
|
119
|
+
from cells.json import dumps, loads
|
|
120
|
+
|
|
121
|
+
payload = dumps({"b": 1, "a": 2}, sort_keys=True, indent=2)
|
|
122
|
+
data = loads('{"amount": 19.95}', parse_float=Decimal, backend="json")
|
|
123
|
+
|
|
124
|
+
assert data["amount"] == Decimal("19.95")
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Backend-native behavior can also differ for non-finite numbers, integer ranges, and dictionary keys. Choose the backend explicitly when these details matter to your data contract.
|
|
128
|
+
|
|
129
|
+
## Supported type conversions
|
|
130
|
+
|
|
131
|
+
These conversions describe `UniversalSerializer` and the recursive API. The adapter may use `orjson`'s native support for types that backend already handles.
|
|
132
|
+
|
|
133
|
+
| Python type | JSON representation |
|
|
134
|
+
| --- | --- |
|
|
135
|
+
| `datetime`, `date`, `time` | ISO-formatted string |
|
|
136
|
+
| `timedelta` | Total seconds as a number |
|
|
137
|
+
| `Decimal` | Floating-point number |
|
|
138
|
+
| `UUID` | String |
|
|
139
|
+
| `Enum` | Its `value`, serialized in turn |
|
|
140
|
+
| `Path` | POSIX-style path string |
|
|
141
|
+
| `set`, `tuple` | Array |
|
|
142
|
+
| NumPy `ndarray` / scalar | Nested lists / native Python value |
|
|
143
|
+
| pandas `DataFrame` | Array of row records |
|
|
144
|
+
| Named pandas `Series` | Object mapping its stringified name to a value list |
|
|
145
|
+
| Unnamed pandas `Series` | Index-to-value mapping |
|
|
146
|
+
| Custom object | `to_dict()`, then `__dict__`, then `__slots__`, subject to configuration |
|
|
147
|
+
|
|
148
|
+
`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.
|
|
149
|
+
|
|
150
|
+
### Custom objects and unknown types
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
from cells.json import UniversalSerializer
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class User:
|
|
157
|
+
def __init__(self, name):
|
|
158
|
+
self.name = name
|
|
159
|
+
|
|
160
|
+
def to_dict(self):
|
|
161
|
+
return {"name": self.name}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
serializer = UniversalSerializer()
|
|
165
|
+
payload = serializer.dumps(User("Alice"))
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
- `strict=True` disables automatic custom-object inspection, including `to_dict()`. Built-in supported conversions remain available.
|
|
169
|
+
- `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.
|
|
170
|
+
- `use_dict=False` disables `__dict__` and `__slots__` inspection while leaving `to_dict()` available outside strict mode.
|
|
171
|
+
- `UniversalSerializer(default=callback)` supplies a fallback for unhandled types.
|
|
172
|
+
|
|
173
|
+
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.
|
|
174
|
+
|
|
175
|
+
## Circular references
|
|
176
|
+
|
|
177
|
+
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`.
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
from cells.json import CircularReferenceError, safe_json_dumps
|
|
181
|
+
|
|
182
|
+
node = {}
|
|
183
|
+
node["self"] = node
|
|
184
|
+
|
|
185
|
+
payload = safe_json_dumps(node)
|
|
186
|
+
assert "<CircularReference dict>" in payload
|
|
187
|
+
|
|
188
|
+
try:
|
|
189
|
+
safe_json_dumps(node, fail_on_circular=True)
|
|
190
|
+
except CircularReferenceError:
|
|
191
|
+
pass
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
`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.
|
|
195
|
+
|
|
196
|
+
`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.
|
|
197
|
+
|
|
198
|
+
## Files and utilities
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
from pathlib import Path
|
|
202
|
+
from cells.json import dump, load
|
|
203
|
+
from cells.json.utils import load_json, save_json
|
|
204
|
+
|
|
205
|
+
path = Path("settings.json")
|
|
206
|
+
|
|
207
|
+
with path.open("w", encoding="utf-8") as stream:
|
|
208
|
+
dump({"enabled": True}, stream, indent=2)
|
|
209
|
+
|
|
210
|
+
with path.open("r", encoding="utf-8") as stream:
|
|
211
|
+
data = load(stream)
|
|
212
|
+
|
|
213
|
+
save_json({"enabled": True}, "output/settings.json", indent=2)
|
|
214
|
+
data = load_json("output/settings.json")
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
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`.
|
|
218
|
+
|
|
219
|
+
Additional helpers:
|
|
220
|
+
|
|
221
|
+
- `prettify_json(data, indent=2)`: serializes a Python value with indentation through `safe_json_dumps()`; also exported from `cells.json`.
|
|
222
|
+
- `JsonSerializable`: base class providing `to_dict()`, `to_json()`, and `from_dict()`.
|
|
223
|
+
- `@json_serializable`: decorator adding the same methods to a class.
|
|
224
|
+
|
|
225
|
+
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.
|
|
226
|
+
|
|
227
|
+
## Error handling
|
|
228
|
+
|
|
229
|
+
```python
|
|
230
|
+
from cells.json import JSONDecodeError, JSONEncodeError, dumps, loads
|
|
231
|
+
|
|
232
|
+
try:
|
|
233
|
+
dumps(object(), strict=True)
|
|
234
|
+
except JSONEncodeError as exc:
|
|
235
|
+
print(exc.obj_type, str(exc))
|
|
236
|
+
|
|
237
|
+
try:
|
|
238
|
+
loads("{invalid}")
|
|
239
|
+
except JSONDecodeError as exc:
|
|
240
|
+
print(exc.pos, exc.msg)
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
`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.
|
|
244
|
+
|
|
245
|
+
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"`.
|
|
246
|
+
|
|
247
|
+
## Development and performance
|
|
248
|
+
|
|
249
|
+
From a local checkout, using Python 3.14:
|
|
250
|
+
|
|
251
|
+
```bash
|
|
252
|
+
python -m pip install -e .
|
|
253
|
+
python -m pip install pytest
|
|
254
|
+
python -m pytest tests/test_serializer.py -v
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
Tests for NumPy and pandas return early when those optional packages are absent. Install them separately to exercise those conversions.
|
|
258
|
+
|
|
259
|
+
Run the included benchmark with:
|
|
260
|
+
|
|
261
|
+
```bash
|
|
262
|
+
python tests/test_performance.py
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
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.
|
|
266
|
+
|
|
267
|
+
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.
|
|
268
|
+
|
|
269
|
+
Performance depends on the payload, backend, conversion path, options, and environment. The benchmark is a local comparison tool; no fixed speedup is guaranteed.
|
|
270
|
+
|
|
271
|
+
## License
|
|
272
|
+
|
|
273
|
+
The package metadata declares the Mozilla Public License 2.0 (`MPL-2.0`).
|
|
@@ -0,0 +1,254 @@
|
|
|
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
|
+
Use **Python 3.14** for the current source tree: it uses exception syntax introduced in Python 3.14. Package metadata currently declares `Python >=3.9`; that declaration does not reflect the syntax requirement of the current source. The CI test job is configured for Python 3.14 on Linux and Windows.
|
|
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
|
+
Unsupported options do not trigger an automatic backend switch. Select `backend="json"` when standard-library parameter semantics are required.
|
|
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=2` | Supported; other non-`None` indentation values require `backend="json"` |
|
|
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
|
+
| `allow_nan=False` | Requires `backend="json"` |
|
|
93
|
+
| Custom encoder/decoder `cls` | Requires `backend="json"` |
|
|
94
|
+
| `object_hook`, `object_pairs_hook`, `parse_float`, `parse_int`, `parse_constant` | Require `backend="json"` |
|
|
95
|
+
|
|
96
|
+
For example, use the standard-library backend to preserve decimal values while parsing:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
from decimal import Decimal
|
|
100
|
+
from cells.json import dumps, loads
|
|
101
|
+
|
|
102
|
+
payload = dumps({"b": 1, "a": 2}, sort_keys=True, indent=2)
|
|
103
|
+
data = loads('{"amount": 19.95}', parse_float=Decimal, backend="json")
|
|
104
|
+
|
|
105
|
+
assert data["amount"] == Decimal("19.95")
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Backend-native behavior can also differ for non-finite numbers, integer ranges, and dictionary keys. Choose the backend explicitly when these details matter to your data contract.
|
|
109
|
+
|
|
110
|
+
## Supported type conversions
|
|
111
|
+
|
|
112
|
+
These conversions describe `UniversalSerializer` and the recursive API. The adapter may use `orjson`'s native support for types that backend already handles.
|
|
113
|
+
|
|
114
|
+
| Python type | JSON representation |
|
|
115
|
+
| --- | --- |
|
|
116
|
+
| `datetime`, `date`, `time` | ISO-formatted string |
|
|
117
|
+
| `timedelta` | Total seconds as a number |
|
|
118
|
+
| `Decimal` | Floating-point number |
|
|
119
|
+
| `UUID` | String |
|
|
120
|
+
| `Enum` | Its `value`, serialized in turn |
|
|
121
|
+
| `Path` | POSIX-style path string |
|
|
122
|
+
| `set`, `tuple` | Array |
|
|
123
|
+
| NumPy `ndarray` / scalar | Nested lists / native Python value |
|
|
124
|
+
| pandas `DataFrame` | Array of row records |
|
|
125
|
+
| Named pandas `Series` | Object mapping its stringified name to a value list |
|
|
126
|
+
| Unnamed pandas `Series` | Index-to-value mapping |
|
|
127
|
+
| Custom object | `to_dict()`, then `__dict__`, then `__slots__`, subject to configuration |
|
|
128
|
+
|
|
129
|
+
`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.
|
|
130
|
+
|
|
131
|
+
### Custom objects and unknown types
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from cells.json import UniversalSerializer
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class User:
|
|
138
|
+
def __init__(self, name):
|
|
139
|
+
self.name = name
|
|
140
|
+
|
|
141
|
+
def to_dict(self):
|
|
142
|
+
return {"name": self.name}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
serializer = UniversalSerializer()
|
|
146
|
+
payload = serializer.dumps(User("Alice"))
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
- `strict=True` disables automatic custom-object inspection, including `to_dict()`. Built-in supported conversions remain available.
|
|
150
|
+
- `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.
|
|
151
|
+
- `use_dict=False` disables `__dict__` and `__slots__` inspection while leaving `to_dict()` available outside strict mode.
|
|
152
|
+
- `UniversalSerializer(default=callback)` supplies a fallback for unhandled types.
|
|
153
|
+
|
|
154
|
+
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.
|
|
155
|
+
|
|
156
|
+
## Circular references
|
|
157
|
+
|
|
158
|
+
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`.
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
from cells.json import CircularReferenceError, safe_json_dumps
|
|
162
|
+
|
|
163
|
+
node = {}
|
|
164
|
+
node["self"] = node
|
|
165
|
+
|
|
166
|
+
payload = safe_json_dumps(node)
|
|
167
|
+
assert "<CircularReference dict>" in payload
|
|
168
|
+
|
|
169
|
+
try:
|
|
170
|
+
safe_json_dumps(node, fail_on_circular=True)
|
|
171
|
+
except CircularReferenceError:
|
|
172
|
+
pass
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`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.
|
|
176
|
+
|
|
177
|
+
`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.
|
|
178
|
+
|
|
179
|
+
## Files and utilities
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
from pathlib import Path
|
|
183
|
+
from cells.json import dump, load
|
|
184
|
+
from cells.json.utils import load_json, save_json
|
|
185
|
+
|
|
186
|
+
path = Path("settings.json")
|
|
187
|
+
|
|
188
|
+
with path.open("w", encoding="utf-8") as stream:
|
|
189
|
+
dump({"enabled": True}, stream, indent=2)
|
|
190
|
+
|
|
191
|
+
with path.open("r", encoding="utf-8") as stream:
|
|
192
|
+
data = load(stream)
|
|
193
|
+
|
|
194
|
+
save_json({"enabled": True}, "output/settings.json", indent=2)
|
|
195
|
+
data = load_json("output/settings.json")
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
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`.
|
|
199
|
+
|
|
200
|
+
Additional helpers:
|
|
201
|
+
|
|
202
|
+
- `prettify_json(data, indent=2)`: serializes a Python value with indentation through `safe_json_dumps()`; also exported from `cells.json`.
|
|
203
|
+
- `JsonSerializable`: base class providing `to_dict()`, `to_json()`, and `from_dict()`.
|
|
204
|
+
- `@json_serializable`: decorator adding the same methods to a class.
|
|
205
|
+
|
|
206
|
+
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.
|
|
207
|
+
|
|
208
|
+
## Error handling
|
|
209
|
+
|
|
210
|
+
```python
|
|
211
|
+
from cells.json import JSONDecodeError, JSONEncodeError, dumps, loads
|
|
212
|
+
|
|
213
|
+
try:
|
|
214
|
+
dumps(object(), strict=True)
|
|
215
|
+
except JSONEncodeError as exc:
|
|
216
|
+
print(exc.obj_type, str(exc))
|
|
217
|
+
|
|
218
|
+
try:
|
|
219
|
+
loads("{invalid}")
|
|
220
|
+
except JSONDecodeError as exc:
|
|
221
|
+
print(exc.pos, exc.msg)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
`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.
|
|
225
|
+
|
|
226
|
+
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"`.
|
|
227
|
+
|
|
228
|
+
## Development and performance
|
|
229
|
+
|
|
230
|
+
From a local checkout, using Python 3.14:
|
|
231
|
+
|
|
232
|
+
```bash
|
|
233
|
+
python -m pip install -e .
|
|
234
|
+
python -m pip install pytest
|
|
235
|
+
python -m pytest tests/test_serializer.py -v
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Tests for NumPy and pandas return early when those optional packages are absent. Install them separately to exercise those conversions.
|
|
239
|
+
|
|
240
|
+
Run the included benchmark with:
|
|
241
|
+
|
|
242
|
+
```bash
|
|
243
|
+
python tests/test_performance.py
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
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.
|
|
247
|
+
|
|
248
|
+
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.
|
|
249
|
+
|
|
250
|
+
Performance depends on the payload, backend, conversion path, options, and environment. The benchmark is a local comparison tool; no fixed speedup is guaranteed.
|
|
251
|
+
|
|
252
|
+
## License
|
|
253
|
+
|
|
254
|
+
The package metadata declares the Mozilla Public License 2.0 (`MPL-2.0`).
|
|
@@ -0,0 +1,44 @@
|
|
|
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 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
|
+
"safe_json_dumps",
|
|
30
|
+
# Exception classes / 异常类
|
|
31
|
+
"JSONSerializationError",
|
|
32
|
+
"JSONEncodeError",
|
|
33
|
+
"JSONDecodeError",
|
|
34
|
+
"CircularReferenceError",
|
|
35
|
+
"UnsupportedTypeError",
|
|
36
|
+
# Adapter (supports multiple JSON backends) / 适配器(支持多种 JSON 后端)
|
|
37
|
+
"JSONAdapter",
|
|
38
|
+
"dump",
|
|
39
|
+
"dumps",
|
|
40
|
+
"load",
|
|
41
|
+
"loads",
|
|
42
|
+
"prettify_json",
|
|
43
|
+
"__VERSION__",
|
|
44
|
+
]
|
|
@@ -4,7 +4,7 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import json
|
|
6
6
|
from functools import lru_cache
|
|
7
|
-
from typing import Any,
|
|
7
|
+
from typing import Any, Union
|
|
8
8
|
|
|
9
9
|
from .exceptions import CircularReferenceError, JSONDecodeError, JSONEncodeError
|
|
10
10
|
from .serializer import UniversalSerializer
|
|
@@ -19,7 +19,7 @@ except ImportError:
|
|
|
19
19
|
orjson = None
|
|
20
20
|
|
|
21
21
|
|
|
22
|
-
_NATIVE_ENCODE_EXCEPTIONS:
|
|
22
|
+
_NATIVE_ENCODE_EXCEPTIONS: tuple[type[Exception], ...] = (TypeError, ValueError)
|
|
23
23
|
_SERIALIZER_CONFIG_KEYS = {
|
|
24
24
|
"strict",
|
|
25
25
|
"ignore_unknown",
|
|
@@ -64,7 +64,7 @@ def _ensure_ascii_json_bytes(json_bytes: bytes) -> bytes:
|
|
|
64
64
|
def _raise_orjson_parameter_error(function_name: str, parameter_name: str) -> None:
|
|
65
65
|
raise TypeError(
|
|
66
66
|
f"{function_name}() does not support parameter '{parameter_name}' with the active orjson backend. "
|
|
67
|
-
f
|
|
67
|
+
f'Use backend="json" for stdlib-compatible handling.'
|
|
68
68
|
)
|
|
69
69
|
|
|
70
70
|
|
|
@@ -118,9 +118,8 @@ def _validate_orjson_dumps_parameters(
|
|
|
118
118
|
option |= getattr(orjson, "OPT_INDENT_2", 0)
|
|
119
119
|
else:
|
|
120
120
|
_raise_orjson_parameter_error("dumps", "indent")
|
|
121
|
-
if separators is not None:
|
|
122
|
-
|
|
123
|
-
_raise_orjson_parameter_error("dumps", "separators")
|
|
121
|
+
if separators is not None and separators != (",", ":"):
|
|
122
|
+
_raise_orjson_parameter_error("dumps", "separators")
|
|
124
123
|
if sort_keys:
|
|
125
124
|
option |= getattr(orjson, "OPT_SORT_KEYS", 0)
|
|
126
125
|
unsupported_keys = [key for key in extra_kwargs if key not in _ORJSON_SAFE_DUMPS_KWARGS]
|
|
@@ -142,7 +141,13 @@ def _validate_orjson_loads_parameters(
|
|
|
142
141
|
if not _is_default_json_decoder(cls):
|
|
143
142
|
_raise_orjson_parameter_error("loads", "cls")
|
|
144
143
|
if object_hook is not None or parse_float is not None or parse_int is not None:
|
|
145
|
-
parameter_name =
|
|
144
|
+
parameter_name = (
|
|
145
|
+
"object_hook"
|
|
146
|
+
if object_hook is not None
|
|
147
|
+
else "parse_float"
|
|
148
|
+
if parse_float is not None
|
|
149
|
+
else "parse_int"
|
|
150
|
+
)
|
|
146
151
|
_raise_orjson_parameter_error("loads", parameter_name)
|
|
147
152
|
if parse_constant is not None or object_pairs_hook is not None:
|
|
148
153
|
parameter_name = "parse_constant" if parse_constant is not None else "object_pairs_hook"
|
|
@@ -157,7 +162,7 @@ class JSONAdapter:
|
|
|
157
162
|
|
|
158
163
|
def __init__(
|
|
159
164
|
self,
|
|
160
|
-
backend:
|
|
165
|
+
backend: str | None = None,
|
|
161
166
|
use_builtin: bool = True,
|
|
162
167
|
**kwargs: Any,
|
|
163
168
|
) -> None:
|
|
@@ -363,8 +368,13 @@ class JSONAdapter:
|
|
|
363
368
|
object_pairs_hook=object_pairs_hook,
|
|
364
369
|
**kwargs,
|
|
365
370
|
)
|
|
366
|
-
except (
|
|
367
|
-
|
|
371
|
+
except (
|
|
372
|
+
json.JSONDecodeError,
|
|
373
|
+
getattr(orjson, "JSONDecodeError", json.JSONDecodeError),
|
|
374
|
+
) as exc:
|
|
375
|
+
raise JSONDecodeError(
|
|
376
|
+
str(exc), getattr(exc, "doc", ""), getattr(exc, "pos", 0)
|
|
377
|
+
) from exc
|
|
368
378
|
|
|
369
379
|
def load(
|
|
370
380
|
self,
|
|
@@ -391,7 +401,9 @@ class JSONAdapter:
|
|
|
391
401
|
|
|
392
402
|
|
|
393
403
|
@lru_cache(maxsize=32)
|
|
394
|
-
def _create_adapter(
|
|
404
|
+
def _create_adapter(
|
|
405
|
+
backend: str, use_builtin: bool, config_items: tuple[tuple[str, Any], ...]
|
|
406
|
+
) -> JSONAdapter:
|
|
395
407
|
return JSONAdapter(backend=backend, use_builtin=use_builtin, **dict(config_items))
|
|
396
408
|
|
|
397
409
|
|