cells-json 0.3.0__tar.gz → 0.3.2__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.2/PKG-INFO +207 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/cells/json/adapter.py +32 -4
- cells_json-0.3.2/cells/json/version.py +1 -0
- cells_json-0.3.2/cells_json.egg-info/PKG-INFO +207 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/setup.py +12 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/tests/test_serializer.py +12 -14
- cells_json-0.3.0/PKG-INFO +0 -15
- cells_json-0.3.0/cells/json/version.py +0 -1
- cells_json-0.3.0/cells_json.egg-info/PKG-INFO +0 -15
- {cells_json-0.3.0 → cells_json-0.3.2}/README.md +0 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/cells/json/__init__.py +0 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/cells/json/exceptions.py +0 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/cells/json/serializer.py +0 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/cells/json/utils.py +0 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/cells_json.egg-info/SOURCES.txt +0 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/cells_json.egg-info/dependency_links.txt +0 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/cells_json.egg-info/not-zip-safe +0 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/cells_json.egg-info/requires.txt +0 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/cells_json.egg-info/top_level.txt +0 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/setup.cfg +0 -0
- {cells_json-0.3.0 → cells_json-0.3.2}/tests/test_performance.py +0 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cells-json
|
|
3
|
+
Version: 0.3.2
|
|
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
|
+
通用 JSON 序列化工具,提供 `orjson` 优先的高性能序列化能力,并补齐 Python 项目中常见的复杂类型处理需求。
|
|
23
|
+
|
|
24
|
+
## 🚀 核心特性
|
|
25
|
+
|
|
26
|
+
- **orjson 优先**:默认使用 `orjson` 作为主后端,优先追求吞吐量和低延迟。
|
|
27
|
+
- **极致性能**:通过适配器模式和类型查找缓存,性能较标准库提升 3x - 10x。
|
|
28
|
+
- **全量类型支持**:原生支持 `datetime`、`Decimal`、`UUID`、`Enum`、`Path`、`numpy`、`pandas`、`set`、`tuple` 等。
|
|
29
|
+
- **工业级异常体系**:提供统一的 `JSONEncodeError` 和 `JSONDecodeError`,兼容标准库并保留完整上下文。
|
|
30
|
+
- **多后端适配**:保留 `backend="json"` 显式回退能力,适合需要标准库参数语义的场景。
|
|
31
|
+
- **防御性设计**:内置循环引用检测(支持标记字符串或严格报错)和显式参数控制。
|
|
32
|
+
- **便捷工具**:提供装饰器、基类和辅助函数简化日常开发。
|
|
33
|
+
|
|
34
|
+
## 📦 安装
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install cells-json
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## 💡 快速开始
|
|
41
|
+
|
|
42
|
+
### 1. 核心 API 导入
|
|
43
|
+
|
|
44
|
+
你可以直接从根包导入最常用的功能:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from cells.json import (
|
|
48
|
+
safe_json_dumps, # 安全序列化(推荐)
|
|
49
|
+
dump, load, # 文件流接口
|
|
50
|
+
dumps, loads, # 高性能适配器
|
|
51
|
+
UniversalSerializer, # 核心转换器
|
|
52
|
+
JSONEncodeError, # 编码异常
|
|
53
|
+
JSONDecodeError # 解码异常
|
|
54
|
+
)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### 2. 通用序列化 (推荐)
|
|
58
|
+
|
|
59
|
+
`safe_json_dumps` 会自动处理常见复杂类型,并采用递归扫描以支持循环引用标记。
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from datetime import datetime
|
|
63
|
+
from cells.json import safe_json_dumps
|
|
64
|
+
|
|
65
|
+
data = {
|
|
66
|
+
"time": datetime.now(),
|
|
67
|
+
"tags": {"python", "json"},
|
|
68
|
+
"meta": {"version": "1.0"}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
# 支持 indent 等标准参数
|
|
72
|
+
json_str = safe_json_dumps(data, indent=2)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### 3. 高性能模式
|
|
76
|
+
|
|
77
|
+
使用 `dumps` 和 `loads` 直接走 `orjson` 主路径。该接口默认统一返回 `str` 类型。
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from cells.json import dumps, loads
|
|
81
|
+
|
|
82
|
+
# 默认优先使用 orjson
|
|
83
|
+
json_str = dumps({"key": "value"}, ensure_ascii=False)
|
|
84
|
+
obj = loads(json_str)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### 4. 标准库风格导入
|
|
88
|
+
|
|
89
|
+
如果你希望在工程里用 `cells` 统一替代标准库入口,可以直接这样写:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from cells import json
|
|
93
|
+
|
|
94
|
+
payload = json.dumps({"name": "alice"}, ensure_ascii=False)
|
|
95
|
+
data = json.loads(payload)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
也支持实例化适配器:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from cells.json import JSONAdapter
|
|
102
|
+
|
|
103
|
+
json = JSONAdapter()
|
|
104
|
+
payload = json.dumps({"name": "alice"}, ensure_ascii=False)
|
|
105
|
+
data = json.loads(payload)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## 后端策略
|
|
109
|
+
|
|
110
|
+
`cells.json` 的接口形状接近标准库 `json`,但行为策略以增强能力为准,不承诺与标准库逐项等价。
|
|
111
|
+
|
|
112
|
+
- 默认 `backend="auto"` 会优先使用 `orjson`。
|
|
113
|
+
- `orjson` 能适配的参数会尽量适配。
|
|
114
|
+
- 无法安全适配的标准库参数会直接报错,并提示显式指定 `backend="json"`。
|
|
115
|
+
|
|
116
|
+
例如:
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from decimal import Decimal
|
|
120
|
+
from cells.json import dumps, loads
|
|
121
|
+
|
|
122
|
+
# orjson 主路径支持的参数
|
|
123
|
+
payload = dumps({"b": 1, "a": 2}, ensure_ascii=False, sort_keys=True, indent=2)
|
|
124
|
+
|
|
125
|
+
# 需要标准库解码钩子时,显式指定 json backend
|
|
126
|
+
data = loads("{\"value\": 1.25}", parse_float=Decimal, backend="json")
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### 当前参数策略
|
|
130
|
+
|
|
131
|
+
- `sort_keys`:在 `orjson` 主路径下已适配。
|
|
132
|
+
- `indent=2`:在 `orjson` 主路径下已适配。
|
|
133
|
+
- `skipkeys=True`:在 `orjson` 主路径下会先做键过滤,再编码。
|
|
134
|
+
- `separators=(",", ":")`:在 `orjson` 主路径下已适配。
|
|
135
|
+
- `check_circular=False`:在 `orjson` 主路径下接受,但不保证行为与标准库一致。
|
|
136
|
+
- `ensure_ascii=True`、`object_hook`、`parse_float`、`parse_int`、`parse_constant`、`object_pairs_hook`、自定义 `cls`:
|
|
137
|
+
需要显式使用 `backend="json"`。
|
|
138
|
+
|
|
139
|
+
## 🔍 场景化指南 (QA)
|
|
140
|
+
|
|
141
|
+
| 场景 | 推荐方案 | 说明 |
|
|
142
|
+
|:---------------|:-------------------------------------------------------|:------------------------------|
|
|
143
|
+
| **标准库报不可序列化** | `safe_json_dumps(data)` | 自动转换 datetime/Decimal/UUID 等 |
|
|
144
|
+
| **遇到未知类型必须报错** | `UniversalSerializer(strict=True).dumps(data)` | 严格校验,防止脏数据入库 |
|
|
145
|
+
| **未知类型自动降级为空** | `UniversalSerializer(ignore_unknown=True).dumps(data)` | 无法处理的字段转为 `null` |
|
|
146
|
+
| **存在循环引用** | `safe_json_dumps(data, fail_on_circular=False)` | 默认模式,返回 `<CircularReference>` |
|
|
147
|
+
| **循环引用必须报错** | `safe_json_dumps(data, fail_on_circular=True)` | 抛出 `CircularReferenceError` |
|
|
148
|
+
| **追求极致吞吐量** | `from cells.json import dumps` | 默认优先走 orjson 主路径 |
|
|
149
|
+
| **美化输出/美化日志** | `from cells.json.utils import prettify_json` | 带缩进和排序的格式化 |
|
|
150
|
+
| **需要标准库解析钩子** | `loads(data, parse_float=Decimal, backend="json")` | 显式切换到标准库后端 |
|
|
151
|
+
|
|
152
|
+
## 📊 性能基准 (Performance)
|
|
153
|
+
|
|
154
|
+
在 Python 3.13 环境下,对比标准库 `json` 的吞吐量表现:
|
|
155
|
+
|
|
156
|
+
| 场景 | 标准 `json.dumps` | `cells-json` (Universal) | 提升倍数 |
|
|
157
|
+
|:-----------------------|:----------------|:-------------------------|:----------|
|
|
158
|
+
| **简单字典** (2k keys) | ~5,800 ops/sec | **~57,000 ops/sec** | **~10x** |
|
|
159
|
+
| **复杂对象** (500 entries) | ~630 ops/sec | **~2,100 ops/sec** | **~3.4x** |
|
|
160
|
+
|
|
161
|
+
> *注:测试包含类型缓存优化。复杂对象场景包含大量 DateTime、Decimal 和 UUID 的混合处理。*
|
|
162
|
+
|
|
163
|
+
## 🛠️ 支持的数据类型
|
|
164
|
+
|
|
165
|
+
- **日期时间**: `datetime`, `date`, `time` (ISO 格式), `timedelta` (总秒数)。
|
|
166
|
+
- **数值与标识**: `Decimal` (float), `UUID` (str), `Enum` (value)。
|
|
167
|
+
- **科学计算**: `numpy` (ndarray/generic), `pandas` (DataFrame/Series)。
|
|
168
|
+
- **容器**: `set`, `tuple` (转换为 list)。
|
|
169
|
+
- **自定义对象**:
|
|
170
|
+
- 优先尝试 `to_dict()` 方法。
|
|
171
|
+
- 其次尝试 `__dict__` 或 `__slots__` 序列化。
|
|
172
|
+
|
|
173
|
+
## ⚠️ 异常处理
|
|
174
|
+
|
|
175
|
+
本库提供了一套完整的、与底层后端解耦的异常体系:
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
from cells.json import JSONEncodeError, JSONDecodeError, CircularReferenceError
|
|
179
|
+
|
|
180
|
+
try:
|
|
181
|
+
payload = dumps(complex_obj)
|
|
182
|
+
except CircularReferenceError as e:
|
|
183
|
+
print(f"检测到循环引用: {e.path}")
|
|
184
|
+
except JSONEncodeError as e:
|
|
185
|
+
print(f"编码失败,对象类型: {e.obj_type}")
|
|
186
|
+
|
|
187
|
+
try:
|
|
188
|
+
data = loads(invalid_str)
|
|
189
|
+
except JSONDecodeError as e:
|
|
190
|
+
# 保留了标准库的错误位置信息
|
|
191
|
+
print(f"解析失败 at pos {e.pos}: {e.msg}")
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
当 `orjson` 主路径不支持某个标准库参数时,会直接抛出 `TypeError`,并提示使用 `backend="json"`。
|
|
195
|
+
|
|
196
|
+
## 📂 辅助工具 (Utils)
|
|
197
|
+
|
|
198
|
+
如需使用以下辅助功能,请从 `cells.json.utils` 导入:
|
|
199
|
+
|
|
200
|
+
- `save_json(data, path)` / `load_json(path)`:快捷文件读写。
|
|
201
|
+
- `prettify_json(data)`:快速生成美化的 JSON 预览。
|
|
202
|
+
- `JsonSerializable` 基类:继承后可使用 `obj.to_json()`。
|
|
203
|
+
- `@json_serializable` 装饰器:为类动态注入 JSON 序列化能力。
|
|
204
|
+
|
|
205
|
+
## 📜 许可证
|
|
206
|
+
|
|
207
|
+
MPL-2.0
|
|
@@ -31,6 +31,36 @@ _ORJSON_SAFE_LOADS_KWARGS = set()
|
|
|
31
31
|
_JSON_BASIC_KEY_TYPES = (str, int, float, bool, type(None))
|
|
32
32
|
|
|
33
33
|
|
|
34
|
+
def _escape_codepoint_for_json_ascii(character: str) -> str:
|
|
35
|
+
codepoint = ord(character)
|
|
36
|
+
if codepoint <= 0xFFFF:
|
|
37
|
+
return f"\\u{codepoint:04x}"
|
|
38
|
+
|
|
39
|
+
codepoint -= 0x10000
|
|
40
|
+
high_surrogate = 0xD800 + (codepoint >> 10)
|
|
41
|
+
low_surrogate = 0xDC00 + (codepoint & 0x3FF)
|
|
42
|
+
return f"\\u{high_surrogate:04x}\\u{low_surrogate:04x}"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _ensure_ascii_json_text(json_text: str) -> str:
|
|
46
|
+
if json_text.isascii():
|
|
47
|
+
return json_text
|
|
48
|
+
|
|
49
|
+
ascii_chunks: list[str] = []
|
|
50
|
+
for character in json_text:
|
|
51
|
+
if character.isascii():
|
|
52
|
+
ascii_chunks.append(character)
|
|
53
|
+
continue
|
|
54
|
+
ascii_chunks.append(_escape_codepoint_for_json_ascii(character))
|
|
55
|
+
return "".join(ascii_chunks)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _ensure_ascii_json_bytes(json_bytes: bytes) -> bytes:
|
|
59
|
+
if json_bytes.isascii():
|
|
60
|
+
return json_bytes
|
|
61
|
+
return _ensure_ascii_json_text(json_bytes.decode("utf-8")).encode("ascii")
|
|
62
|
+
|
|
63
|
+
|
|
34
64
|
def _raise_orjson_parameter_error(function_name: str, parameter_name: str) -> None:
|
|
35
65
|
raise TypeError(
|
|
36
66
|
f"{function_name}() does not support parameter '{parameter_name}' with the active orjson backend. "
|
|
@@ -70,7 +100,6 @@ def _is_default_json_decoder(cls: Any) -> bool:
|
|
|
70
100
|
def _validate_orjson_dumps_parameters(
|
|
71
101
|
*,
|
|
72
102
|
skipkeys: bool,
|
|
73
|
-
ensure_ascii: bool,
|
|
74
103
|
check_circular: bool,
|
|
75
104
|
allow_nan: bool,
|
|
76
105
|
cls: Any,
|
|
@@ -80,8 +109,6 @@ def _validate_orjson_dumps_parameters(
|
|
|
80
109
|
extra_kwargs: dict[str, Any],
|
|
81
110
|
) -> int:
|
|
82
111
|
option = 0
|
|
83
|
-
if ensure_ascii:
|
|
84
|
-
_raise_orjson_parameter_error("dumps", "ensure_ascii")
|
|
85
112
|
if not allow_nan:
|
|
86
113
|
_raise_orjson_parameter_error("dumps", "allow_nan")
|
|
87
114
|
if not _is_default_json_encoder(cls):
|
|
@@ -179,7 +206,6 @@ class JSONAdapter:
|
|
|
179
206
|
if HAS_ORJSON and self._backend != "json":
|
|
180
207
|
validated_option = _validate_orjson_dumps_parameters(
|
|
181
208
|
skipkeys=skipkeys,
|
|
182
|
-
ensure_ascii=ensure_ascii,
|
|
183
209
|
check_circular=check_circular,
|
|
184
210
|
allow_nan=allow_nan,
|
|
185
211
|
cls=cls,
|
|
@@ -195,6 +221,8 @@ class JSONAdapter:
|
|
|
195
221
|
option=validated_option if option is None else (option | validated_option),
|
|
196
222
|
**kwargs,
|
|
197
223
|
)
|
|
224
|
+
if ensure_ascii:
|
|
225
|
+
result = _ensure_ascii_json_bytes(result)
|
|
198
226
|
else:
|
|
199
227
|
result = self._json_dumps(
|
|
200
228
|
obj,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__VERSION__ = "0.3.2"
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cells-json
|
|
3
|
+
Version: 0.3.2
|
|
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
|
+
通用 JSON 序列化工具,提供 `orjson` 优先的高性能序列化能力,并补齐 Python 项目中常见的复杂类型处理需求。
|
|
23
|
+
|
|
24
|
+
## 🚀 核心特性
|
|
25
|
+
|
|
26
|
+
- **orjson 优先**:默认使用 `orjson` 作为主后端,优先追求吞吐量和低延迟。
|
|
27
|
+
- **极致性能**:通过适配器模式和类型查找缓存,性能较标准库提升 3x - 10x。
|
|
28
|
+
- **全量类型支持**:原生支持 `datetime`、`Decimal`、`UUID`、`Enum`、`Path`、`numpy`、`pandas`、`set`、`tuple` 等。
|
|
29
|
+
- **工业级异常体系**:提供统一的 `JSONEncodeError` 和 `JSONDecodeError`,兼容标准库并保留完整上下文。
|
|
30
|
+
- **多后端适配**:保留 `backend="json"` 显式回退能力,适合需要标准库参数语义的场景。
|
|
31
|
+
- **防御性设计**:内置循环引用检测(支持标记字符串或严格报错)和显式参数控制。
|
|
32
|
+
- **便捷工具**:提供装饰器、基类和辅助函数简化日常开发。
|
|
33
|
+
|
|
34
|
+
## 📦 安装
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install cells-json
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## 💡 快速开始
|
|
41
|
+
|
|
42
|
+
### 1. 核心 API 导入
|
|
43
|
+
|
|
44
|
+
你可以直接从根包导入最常用的功能:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from cells.json import (
|
|
48
|
+
safe_json_dumps, # 安全序列化(推荐)
|
|
49
|
+
dump, load, # 文件流接口
|
|
50
|
+
dumps, loads, # 高性能适配器
|
|
51
|
+
UniversalSerializer, # 核心转换器
|
|
52
|
+
JSONEncodeError, # 编码异常
|
|
53
|
+
JSONDecodeError # 解码异常
|
|
54
|
+
)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### 2. 通用序列化 (推荐)
|
|
58
|
+
|
|
59
|
+
`safe_json_dumps` 会自动处理常见复杂类型,并采用递归扫描以支持循环引用标记。
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from datetime import datetime
|
|
63
|
+
from cells.json import safe_json_dumps
|
|
64
|
+
|
|
65
|
+
data = {
|
|
66
|
+
"time": datetime.now(),
|
|
67
|
+
"tags": {"python", "json"},
|
|
68
|
+
"meta": {"version": "1.0"}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
# 支持 indent 等标准参数
|
|
72
|
+
json_str = safe_json_dumps(data, indent=2)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### 3. 高性能模式
|
|
76
|
+
|
|
77
|
+
使用 `dumps` 和 `loads` 直接走 `orjson` 主路径。该接口默认统一返回 `str` 类型。
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from cells.json import dumps, loads
|
|
81
|
+
|
|
82
|
+
# 默认优先使用 orjson
|
|
83
|
+
json_str = dumps({"key": "value"}, ensure_ascii=False)
|
|
84
|
+
obj = loads(json_str)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### 4. 标准库风格导入
|
|
88
|
+
|
|
89
|
+
如果你希望在工程里用 `cells` 统一替代标准库入口,可以直接这样写:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from cells import json
|
|
93
|
+
|
|
94
|
+
payload = json.dumps({"name": "alice"}, ensure_ascii=False)
|
|
95
|
+
data = json.loads(payload)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
也支持实例化适配器:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from cells.json import JSONAdapter
|
|
102
|
+
|
|
103
|
+
json = JSONAdapter()
|
|
104
|
+
payload = json.dumps({"name": "alice"}, ensure_ascii=False)
|
|
105
|
+
data = json.loads(payload)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## 后端策略
|
|
109
|
+
|
|
110
|
+
`cells.json` 的接口形状接近标准库 `json`,但行为策略以增强能力为准,不承诺与标准库逐项等价。
|
|
111
|
+
|
|
112
|
+
- 默认 `backend="auto"` 会优先使用 `orjson`。
|
|
113
|
+
- `orjson` 能适配的参数会尽量适配。
|
|
114
|
+
- 无法安全适配的标准库参数会直接报错,并提示显式指定 `backend="json"`。
|
|
115
|
+
|
|
116
|
+
例如:
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from decimal import Decimal
|
|
120
|
+
from cells.json import dumps, loads
|
|
121
|
+
|
|
122
|
+
# orjson 主路径支持的参数
|
|
123
|
+
payload = dumps({"b": 1, "a": 2}, ensure_ascii=False, sort_keys=True, indent=2)
|
|
124
|
+
|
|
125
|
+
# 需要标准库解码钩子时,显式指定 json backend
|
|
126
|
+
data = loads("{\"value\": 1.25}", parse_float=Decimal, backend="json")
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### 当前参数策略
|
|
130
|
+
|
|
131
|
+
- `sort_keys`:在 `orjson` 主路径下已适配。
|
|
132
|
+
- `indent=2`:在 `orjson` 主路径下已适配。
|
|
133
|
+
- `skipkeys=True`:在 `orjson` 主路径下会先做键过滤,再编码。
|
|
134
|
+
- `separators=(",", ":")`:在 `orjson` 主路径下已适配。
|
|
135
|
+
- `check_circular=False`:在 `orjson` 主路径下接受,但不保证行为与标准库一致。
|
|
136
|
+
- `ensure_ascii=True`、`object_hook`、`parse_float`、`parse_int`、`parse_constant`、`object_pairs_hook`、自定义 `cls`:
|
|
137
|
+
需要显式使用 `backend="json"`。
|
|
138
|
+
|
|
139
|
+
## 🔍 场景化指南 (QA)
|
|
140
|
+
|
|
141
|
+
| 场景 | 推荐方案 | 说明 |
|
|
142
|
+
|:---------------|:-------------------------------------------------------|:------------------------------|
|
|
143
|
+
| **标准库报不可序列化** | `safe_json_dumps(data)` | 自动转换 datetime/Decimal/UUID 等 |
|
|
144
|
+
| **遇到未知类型必须报错** | `UniversalSerializer(strict=True).dumps(data)` | 严格校验,防止脏数据入库 |
|
|
145
|
+
| **未知类型自动降级为空** | `UniversalSerializer(ignore_unknown=True).dumps(data)` | 无法处理的字段转为 `null` |
|
|
146
|
+
| **存在循环引用** | `safe_json_dumps(data, fail_on_circular=False)` | 默认模式,返回 `<CircularReference>` |
|
|
147
|
+
| **循环引用必须报错** | `safe_json_dumps(data, fail_on_circular=True)` | 抛出 `CircularReferenceError` |
|
|
148
|
+
| **追求极致吞吐量** | `from cells.json import dumps` | 默认优先走 orjson 主路径 |
|
|
149
|
+
| **美化输出/美化日志** | `from cells.json.utils import prettify_json` | 带缩进和排序的格式化 |
|
|
150
|
+
| **需要标准库解析钩子** | `loads(data, parse_float=Decimal, backend="json")` | 显式切换到标准库后端 |
|
|
151
|
+
|
|
152
|
+
## 📊 性能基准 (Performance)
|
|
153
|
+
|
|
154
|
+
在 Python 3.13 环境下,对比标准库 `json` 的吞吐量表现:
|
|
155
|
+
|
|
156
|
+
| 场景 | 标准 `json.dumps` | `cells-json` (Universal) | 提升倍数 |
|
|
157
|
+
|:-----------------------|:----------------|:-------------------------|:----------|
|
|
158
|
+
| **简单字典** (2k keys) | ~5,800 ops/sec | **~57,000 ops/sec** | **~10x** |
|
|
159
|
+
| **复杂对象** (500 entries) | ~630 ops/sec | **~2,100 ops/sec** | **~3.4x** |
|
|
160
|
+
|
|
161
|
+
> *注:测试包含类型缓存优化。复杂对象场景包含大量 DateTime、Decimal 和 UUID 的混合处理。*
|
|
162
|
+
|
|
163
|
+
## 🛠️ 支持的数据类型
|
|
164
|
+
|
|
165
|
+
- **日期时间**: `datetime`, `date`, `time` (ISO 格式), `timedelta` (总秒数)。
|
|
166
|
+
- **数值与标识**: `Decimal` (float), `UUID` (str), `Enum` (value)。
|
|
167
|
+
- **科学计算**: `numpy` (ndarray/generic), `pandas` (DataFrame/Series)。
|
|
168
|
+
- **容器**: `set`, `tuple` (转换为 list)。
|
|
169
|
+
- **自定义对象**:
|
|
170
|
+
- 优先尝试 `to_dict()` 方法。
|
|
171
|
+
- 其次尝试 `__dict__` 或 `__slots__` 序列化。
|
|
172
|
+
|
|
173
|
+
## ⚠️ 异常处理
|
|
174
|
+
|
|
175
|
+
本库提供了一套完整的、与底层后端解耦的异常体系:
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
from cells.json import JSONEncodeError, JSONDecodeError, CircularReferenceError
|
|
179
|
+
|
|
180
|
+
try:
|
|
181
|
+
payload = dumps(complex_obj)
|
|
182
|
+
except CircularReferenceError as e:
|
|
183
|
+
print(f"检测到循环引用: {e.path}")
|
|
184
|
+
except JSONEncodeError as e:
|
|
185
|
+
print(f"编码失败,对象类型: {e.obj_type}")
|
|
186
|
+
|
|
187
|
+
try:
|
|
188
|
+
data = loads(invalid_str)
|
|
189
|
+
except JSONDecodeError as e:
|
|
190
|
+
# 保留了标准库的错误位置信息
|
|
191
|
+
print(f"解析失败 at pos {e.pos}: {e.msg}")
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
当 `orjson` 主路径不支持某个标准库参数时,会直接抛出 `TypeError`,并提示使用 `backend="json"`。
|
|
195
|
+
|
|
196
|
+
## 📂 辅助工具 (Utils)
|
|
197
|
+
|
|
198
|
+
如需使用以下辅助功能,请从 `cells.json.utils` 导入:
|
|
199
|
+
|
|
200
|
+
- `save_json(data, path)` / `load_json(path)`:快捷文件读写。
|
|
201
|
+
- `prettify_json(data)`:快速生成美化的 JSON 预览。
|
|
202
|
+
- `JsonSerializable` 基类:继承后可使用 `obj.to_json()`。
|
|
203
|
+
- `@json_serializable` 装饰器:为类动态注入 JSON 序列化能力。
|
|
204
|
+
|
|
205
|
+
## 📜 许可证
|
|
206
|
+
|
|
207
|
+
MPL-2.0
|
|
@@ -9,6 +9,7 @@ BASE_DIR = Path(__file__).resolve().parent
|
|
|
9
9
|
DIST_NAME = "cells-json"
|
|
10
10
|
MODULE_ROOT = "cells"
|
|
11
11
|
VERSION_FILE = BASE_DIR / MODULE_ROOT / "json" / "version.py"
|
|
12
|
+
README_FILE = BASE_DIR / "README.md"
|
|
12
13
|
|
|
13
14
|
|
|
14
15
|
def build_version() -> str:
|
|
@@ -25,11 +26,20 @@ def read_version(version_file: Path) -> str:
|
|
|
25
26
|
return match.group(1)
|
|
26
27
|
|
|
27
28
|
|
|
29
|
+
def read_readme(readme_file: Path) -> str:
|
|
30
|
+
"""Read the project README for package metadata."""
|
|
31
|
+
return readme_file.read_text(encoding="utf-8")
|
|
32
|
+
|
|
33
|
+
|
|
28
34
|
try:
|
|
29
35
|
version = read_version(VERSION_FILE)
|
|
30
36
|
except Exception:
|
|
31
37
|
version = build_version()
|
|
32
38
|
|
|
39
|
+
try:
|
|
40
|
+
long_description = read_readme(README_FILE)
|
|
41
|
+
except Exception:
|
|
42
|
+
long_description = "Orjson-first JSON serialization utilities for the cells namespace."
|
|
33
43
|
|
|
34
44
|
setup(
|
|
35
45
|
name=DIST_NAME,
|
|
@@ -38,6 +48,8 @@ setup(
|
|
|
38
48
|
author="HarmonSir",
|
|
39
49
|
author_email="git@pylab.me",
|
|
40
50
|
description="Orjson-first JSON serialization utilities for the cells namespace",
|
|
51
|
+
long_description=long_description,
|
|
52
|
+
long_description_content_type="text/markdown",
|
|
41
53
|
packages=find_namespace_packages(include=[f"{MODULE_ROOT}.*"]),
|
|
42
54
|
include_package_data=True,
|
|
43
55
|
zip_safe=False,
|
|
@@ -444,21 +444,19 @@ def test_orjson_indent_and_sort_keys():
|
|
|
444
444
|
print("✓ orjson 参数适配测试通过")
|
|
445
445
|
|
|
446
446
|
|
|
447
|
-
def
|
|
448
|
-
"""
|
|
449
|
-
print("测试 dumps
|
|
447
|
+
def test_orjson_ensure_ascii_is_adapted():
|
|
448
|
+
"""测试 ensure_ascii=True 在 orjson 主路径下会做兼容转换"""
|
|
449
|
+
print("测试 dumps ensure_ascii 适配...")
|
|
450
|
+
result = dumps({"name": "中文", "emoji": "😀"}, ensure_ascii=True)
|
|
451
|
+
assert result.isascii()
|
|
452
|
+
assert "\\u4e2d\\u6587" in result
|
|
453
|
+
assert "\\ud83d\\ude00" in result
|
|
454
|
+
parsed = loads(result)
|
|
455
|
+
assert parsed == {"name": "中文", "emoji": "😀"}
|
|
450
456
|
if not HAS_ORJSON:
|
|
451
|
-
|
|
452
|
-
assert "\\u4e2d\\u6587" in result
|
|
453
|
-
print("⊘ orjson 未安装,auto 已退回 json backend")
|
|
457
|
+
print("⊘ orjson 未安装,当前由 json backend 原生处理")
|
|
454
458
|
return
|
|
455
|
-
|
|
456
|
-
dumps({"name": "中文"}, ensure_ascii=True)
|
|
457
|
-
assert False, "应该提示显式指定 json backend"
|
|
458
|
-
except TypeError as exc:
|
|
459
|
-
assert "backend=\"json\"" in str(exc)
|
|
460
|
-
assert "ensure_ascii" in str(exc)
|
|
461
|
-
print("✓ dumps 不支持参数报错测试通过")
|
|
459
|
+
print("✓ dumps ensure_ascii 适配测试通过")
|
|
462
460
|
|
|
463
461
|
|
|
464
462
|
def test_orjson_skipkeys_is_adapted():
|
|
@@ -533,7 +531,7 @@ def run_all_tests():
|
|
|
533
531
|
test_parse_float_requires_json_backend()
|
|
534
532
|
test_adapter_instance_stdlib_signature()
|
|
535
533
|
test_orjson_indent_and_sort_keys()
|
|
536
|
-
|
|
534
|
+
test_orjson_ensure_ascii_is_adapted()
|
|
537
535
|
test_orjson_skipkeys_is_adapted()
|
|
538
536
|
test_orjson_compact_separators_is_adapted()
|
|
539
537
|
test_orjson_check_circular_false_is_accepted()
|
cells_json-0.3.0/PKG-INFO
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: cells-json
|
|
3
|
-
Version: 0.3.0
|
|
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
|
-
Requires-Dist: orjson
|
|
10
|
-
Dynamic: author
|
|
11
|
-
Dynamic: author-email
|
|
12
|
-
Dynamic: license
|
|
13
|
-
Dynamic: requires-dist
|
|
14
|
-
Dynamic: requires-python
|
|
15
|
-
Dynamic: summary
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__VERSION__ = "0.3.0"
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: cells-json
|
|
3
|
-
Version: 0.3.0
|
|
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
|
-
Requires-Dist: orjson
|
|
10
|
-
Dynamic: author
|
|
11
|
-
Dynamic: author-email
|
|
12
|
-
Dynamic: license
|
|
13
|
-
Dynamic: requires-dist
|
|
14
|
-
Dynamic: requires-python
|
|
15
|
-
Dynamic: summary
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|