数据格式:保留类型、缺失和十进制数值
Data formats and serialization
定义一种记录协议,通过 CSV 与 JSON 往返,拒绝悄悄改变数据含义。
data-formats文件能打开,含义却可能已经变了
测量档案导出三条记录:一个 ID 是 0007,一个读数缺失,一个备注为空,另一个备注带逗号、换行和引号。还有一个十进制读数为 9007199254740993.01。
不仔细的导入会把 ID 变成 7,把缺失读数当成零,把备注拆成多条记录,或者将十进制数舍入。文件可能仍然符合语法,但序列化已经没有保住应用的数据模型。
本章定义一种小型记录协议,分别编码为 CSV 和 JSON。两者都要保留记录顺序、ID 与备注的精确字符串、缺失位置,以及十进制数值。它是服务于明确结构的编解码器,不是导出任意 Python 对象的通用工具。
先定义类型和缺失,再选择标点
逻辑记录
记录包括非空字符串 ID、有限 Decimal 或 None 类型的读数,以及可以为空的字符串备注。同一集合内 ID 唯一。None 表示“未提供读数”,不同于十进制零,也不同于空备注。
有限十进制数由符号、系数和指数表示:
编解码器把读数存为定点十进制文本,直接将文本解析成 Decimal,中间不经过二进制浮点,就能保留数值。它不承诺保留全部原始指数或有效位标记:Decimal('1E+3') 会成为文本 1000。如果小数位数本身有业务含义,应另设字段,或明确编码十进制元组。Python 的 decimal 文档区分了数值、有效位与算术上下文。
同一条记录的两种表示
| 逻辑字段 | CSV 协议 | JSON 协议 |
|---|---|---|
| ID | id 文本列 | id 字符串成员 |
| 存在读数 | reading_present 为 1,reading 保存十进制文本 | reading 为十进制字符串 |
| 缺失读数 | reading_present 为 0,reading 必须为空 | reading 为 null |
| 备注 | 文本,必要时按 CSV 规则加引号 | 字符串,必要时按 JSON 规则转义 |
| 版本 | 这份精确的四列表头就是 CSV 版本 1 契约 | 顶层整数 schema 等于 1 |
CSV 本身不提供这些字段类型。Python CSV 文档说明了普通解析器返回字符串及其引号规则;存在标记和数据结构则由应用补上。若直接把 None 交给 CSV writer,会得到空字段;周围协议若不恢复含义,区别就丢失了。
JSON 有 null,也区分字符串和数值,但数值语法不要求所有消费者都采用任意精度。RFC 8259讨论了数值互操作限制,以及重复成员名处理方式的不确定性。本协议使用十进制字符串,拒绝数值类型的读数与重复成员,并要求所有声明字段都出现。缺少 reading 键是不合格记录;明确写出 null 则是合法缺失读数。
往返需要明确的等价关系
对合法记录,要求:
这里的等价指记录顺序、字符串内容、缺失位置与精确十进制数值相同,不要求原文件字节、引号选择、JSON 成员顺序或 Decimal 指数元数据都相同。判断往返测试是否充分,必须先说明这一点。
只做往返检查还不够:编码器和解码器可能犯同一个错误。还应独立查看传输表示,测试手写输入,并用另一种精确表示核对数值。
理解结构的 CSV 与 JSON 编解码器
以下 Python 3.12 程序只使用标准库,返回文本或 Record 对象元组。若要写文件,应明确采用 UTF-8;直接给 CSV reader/writer 提供文本文件时,应设置 newline=''。本例的 StringIO 已采用该换行约定。
记录集合必须是由普通 Record 实例组成的列表或元组,允许空集合。ID 与备注必须是能编码为 UTF-8、至多 4096 个字符的字符串。CSV 函数要求解释器的字段解析上限至少为 4096,不会修改这个全局设置。读数必须为有限 Decimal:系数至多 80 位、指数介于 −20 与 20、定点输出不超过 80 个字符。这些教学限制约束单个数字的转换。传输中的十进制文本允许可选负号、普通整数位和可选小数部分;不允许正号、指数写法、多余前导零或空白。
两个解码器都会验证全部记录。未知或缺少的 JSON 字段、错误类型、重复 ID、不一致的 CSV 存在标记及不支持的版本都会失败。重复 JSON 键与非标准 NaN、Infinity 字面量在解析阶段被拒绝。普通语法或取值错误引发 ValueError;本实现不是流式解析器,也不为无限量输入提供资源隔离。
import csv
from dataclasses import dataclass
from decimal import Decimal
import io
import json
import re
@dataclass(frozen=True)
class Record:
identity: str
reading: Decimal | None
note: str
HEADER = ['id', 'reading_present', 'reading', 'note']
def _text(value, nonempty=False, max_chars=None):
if type(value) is not str or (nonempty and not value):
raise ValueError('text field has the wrong type or is empty')
if max_chars is not None and len(value) > max_chars:
raise ValueError('text field exceeds the protocol character limit')
try:
value.encode('utf-8')
except UnicodeEncodeError as exc:
raise ValueError('text must encode as UTF-8') from exc
return value
def _decimal_text(value):
if type(value) is not Decimal or not value.is_finite():
raise ValueError('reading must be finite Decimal or None')
parts = value.as_tuple()
if abs(parts.exponent) > 20 or len(parts.digits) > 80:
raise ValueError('decimal representation exceeds the teaching limit')
text = format(value, 'f')
if len(text) > 80:
raise ValueError('fixed decimal text exceeds 80 characters')
return text
def _read_decimal(text):
if type(text) is not str or len(text) > 80 or re.fullmatch(r'-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?', text) is None:
raise ValueError('expected fixed-point decimal text')
value = Decimal(text)
_decimal_text(value)
return value
def _records(records):
if type(records) not in (list, tuple):
raise ValueError('records must be a list or tuple')
seen = set()
result = []
for row in records:
if type(row) is not Record:
raise ValueError('expected Record objects')
_text(row.identity, nonempty=True, max_chars=4096)
_text(row.note, max_chars=4096)
if row.identity in seen:
raise ValueError('record IDs must be unique')
seen.add(row.identity)
if row.reading is not None:
_decimal_text(row.reading)
result.append(row)
return tuple(result)
def encode_csv(records):
if csv.field_size_limit() < 4096:
raise ValueError('CSV parser field limit must be at least 4096')
records = _records(records)
out = io.StringIO(newline='')
writer = csv.writer(out, lineterminator='\r\n')
writer.writerow(HEADER)
for row in records:
present = row.reading is not None
writer.writerow([row.identity, '1' if present else '0',
_decimal_text(row.reading) if present else '', row.note])
return out.getvalue()
def decode_csv(text):
if csv.field_size_limit() < 4096:
raise ValueError('CSV parser field limit must be at least 4096')
_text(text)
reader = csv.reader(io.StringIO(text, newline=''), strict=True)
result = []
try:
if next(reader, None) != HEADER:
raise ValueError('unexpected CSV header')
for fields in reader:
if len(fields) != 4:
raise ValueError('expected four CSV fields')
identity, present, reading, note = fields
if present not in ('0', '1') or (present == '0' and reading != ''):
raise ValueError('invalid CSV presence marker or missing-value payload')
value = _read_decimal(reading) if present == '1' else None
result.append(Record(identity, value, note))
except csv.Error as exc:
raise ValueError('malformed CSV') from exc
return _records(result)
def encode_json(records):
records = _records(records)
payload = {'schema': 1, 'records': [
{'id': row.identity, 'reading': None if row.reading is None else _decimal_text(row.reading),
'note': row.note} for row in records]}
return json.dumps(payload, ensure_ascii=False, allow_nan=False,
sort_keys=True, separators=(',', ':'))
def _unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError('duplicate JSON member')
result[key] = value
return result
def _no_constant(value):
raise ValueError('nonstandard JSON numeric constant')
def decode_json(text):
_text(text)
payload = json.loads(text, object_pairs_hook=_unique_object, parse_constant=_no_constant)
if type(payload) is not dict or set(payload) != {'schema', 'records'}:
raise ValueError('unexpected JSON envelope')
if type(payload['schema']) is not int or payload['schema'] != 1 or type(payload['records']) is not list:
raise ValueError('unsupported schema or records type')
result = []
for row in payload['records']:
if type(row) is not dict or set(row) != {'id', 'reading', 'note'}:
raise ValueError('unexpected JSON record fields')
value = None if row['reading'] is None else _read_decimal(row['reading'])
result.append(Record(row['id'], value, row['note']))
return _records(result)
if __name__ == '__main__':
rows = (Record('0007', Decimal('9007199254740993.01'), 'sensor, east'),
Record('0008', None, ''), Record('0009', Decimal('-0.00'), 'line 1\nline "2"'))
csv_text, json_text = encode_csv(rows), encode_json(rows)
print('CSV wire', repr(csv_text))
print('JSON wire', json_text)
print('CSV round trip', decode_csv(csv_text) == rows)
print('JSON round trip', decode_json(json_text) == rows)
print('missing / zero', decode_json(json_text)[1].reading is None, decode_json(json_text)[2].reading == 0)
print('float round trip exact', Decimal(float(rows[0].reading)) == rows[0].reading)
try:
decode_json('{"schema":1,"schema":2,"records":[]}')
except ValueError:
print('duplicate JSON member rejected', True)
输出:
CSV wire 'id,reading_present,reading,note\r\n0007,1,9007199254740993.01,"sensor, east"\r\n0008,0,,\r\n0009,1,-0.00,"line 1\nline ""2"""\r\n'
JSON wire {"records":[{"id":"0007","note":"sensor, east","reading":"9007199254740993.01"},{"id":"0008","note":"","reading":null},{"id":"0009","note":"line 1\nline \"2\"","reading":"-0.00"}],"schema":1}
CSV round trip True
JSON round trip True
missing / zero True True
float round trip exact False
duplicate JSON member rejected True
ID 0007 仍为文本,缺失读数仍为 None,而 -0.00 仍是存在的零值。包含引号的备注在两种编码后都保留了嵌入换行。CSV 输出通过 Python repr 展示,因此可见的 \r\n 表示返回字符串中实际存在的记录结束字符。
十进制读数也完整通过了两种编解码器。单独的浮点转换却未通过精确值比较,因为解码器还没开始工作,信息就已经丢失了。由已舍入浮点数构造 Decimal,保留的是那个浮点值,不是原来的十进制文本。Decimal 构造行为
对合法集合,设 B 为处理或产生的总文本大小,N 为记录数。在数值字段有界、字典与集合操作按期望成本计费时,每个编解码器需要 O(B+N+1) 工作与 O(B+N+1) 内存,包括完整文本和记录表示。程序保留记录顺序,不排序整个集合;它会将全部输入、输出具体化到内存中,没有宣称流式内存用量。
格式不会提供完整协议
这份结构仍需要外部含义。记录没有说明测量单位、采集时间、校准版本或读数为何缺失。应用需要这些信息时,应增加字段并定义迁移,不能悄悄改变版本 1。拒绝未知字段能防止旧读者装作理解新记录,但也意味着兼容性改动需要明确安排。
在电子表格里打开 CSV,可能触发忽略本协议的自动类型推断。只有消费者遵守文本类型声明,前导零 ID 与高精度读数才有保障。另一个 JSON 消费者也必须知道 reading 是十进制字符串,而不是一般描述文字。保住含义的是生产者与消费者之间的约定。
十进制存储避免了交换边界上的二进制转换,但不保证后续任意上下文中的算术都精确。除法或乘法仍可能按配置精度舍入。本编解码器不对读数做算术。定点表示保留数值;需要有效位元数据的应用,应采用更丰富的结构。
对于大表,逐行文本的解析成本可能较高,按列选择也不方便;对于数组,还要表示形状和数据类型。这些理由支持根据实际负载评估带类型的二进制格式,而不是以为换个扩展名,就解决了缺失、单位或兼容性问题。
找出可能消失的信息
- CSV 已经有读数列,为什么还要
reading_present?
答案:空字段没有通用的缺失含义。明确的标记区分缺失读数与存在的十进制值,还能让解码器拒绝矛盾输入,例如标记为 0,负载却是 12.5。空备注仍然是独立的文本值。
- 消费者把十进制字符串转为浮点数,再从该浮点数构造
Decimal。这遵守了精度契约吗?
答案:没有。二进制转换可能丢掉十进制信息。消费者应直接从字符串构造精确十进制表示;后来的精确转换不能推断已经丢掉的数字。
{"id":"0007","id":"0008"}应不应该保留最后一个 ID 并接受?
答案:本协议不接受重复成员名,避免记录含义取决于解析器采用第一个值还是最后一个值。这个对象还缺少必需字段;任意一项缺陷都足以拒绝它。
Decimal('1E+3')返回后变成Decimal('1000'),往返契约失败了吗?如果原指数承载测量有效位信息呢?
答案:数值保留,所以本契约成功;它有意不保留全部指数与有效位元数据。如果这些信息重要,应在修订后的结构中保存小数位数,或符号、系数、指数元组,并测试更强的等价关系。
标准定义语法,应用决定语义
RFC 8259定义 JSON 的值类型,并记录互操作问题。Python JSON 参考提供解析钩子和序列化选项,使本例能够执行更严格的重复键与数值策略。两份资料都不会规定测量 ID 或缺失读数的业务含义。
CSV 参考解释引号与换行处理,decimal 参考解释数值和有效位。应把它们与应用结构一起阅读。可继续查阅数据框中的按列操作,以及实验复现,将保存产物与生成它的代码和输入关联起来。
先判断,再看解释
结构要求 reading 键存在,但值可以为 null。哪种输入表示合法缺失读数?
学习目标
- 定义记录类型,区分缺失、零、空文本与缺少字段。
- 通过 CSV 与 JSON 保留十进制数值和字符串身份。
- 独立检验语义往返,避免编码器和解码器共享错误。
先修与延伸
查看知识关联图 →参考文献
- csv — CSV File Reading and Writing — Python 3.12
Python Software Foundation and Python contributors - json — JSON Encoder and Decoder — Python 3.12
Python Software Foundation and Python contributors - decimal — Decimal Fixed-point and Floating-point Arithmetic — Python 3.12
Python Software Foundation and Python contributors - RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format
Tim Bray, editor; IETF · 2017
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-06 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- 7 项测试在 CPython 3.12.12 和 3.12.4 下通过。手写 CSV/JSON 样例核查精确输出与独立解码;8 条记录的传输数值用整数位数到 Fraction 的解析独立于 Decimal 解码核对,同时检查 ID、备注、存在标记、null 与类型。
- 核查 4096 字符字段边界、CSV 所需解析上限及不修改该设置、空集合、两套编解码、重新编码、80 字符数字边界、指数元数据改变但数值保留、两位精度上下文、Unicode/引号/换行、重复及转义后等价 JSON 键、非法存在标记、错误类型、不支持版本及非有限值。实际复现七行输出。
- 完整原创双语同 Python、2 对显示式、6 锚点、4 已答练习。严格 MDX/KaTeX 与实际 React HTML 通过。按 Humanizer 复读;仅 AI 作者检查,written 待独立审校。完整内存编解码器,不声称通用对象序列化或流式处理,仅草稿文件。
- Root 完整读取双语和编解码器,核对两公式、明确的往返等价关系、四答案与六锚点。在 CPython 3.12.4 重跑七项作者测试及严格 MDX/KaTeX/React HTML 通过,五项冻结哈希匹配,无需修订。
- 核查并重跑作者已有手写传输样例与整数/Fraction 独立数值参照,不再添加重复参照。复核结构/类型拒绝、明确缺失、前导零身份、UTF-8 与 CSV 字段边界、Decimal 编解码定义域闭合及有效位信息损失;期望哈希操作成本与完整物化说明符合有界协议。
- 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
- 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。
核对的来源位置:
- csv — CSV File Reading and Writing — Python 3.12 · Actually read official 3.12 reference: reader string results/newline handling, writer conversion of None to an empty string at lines 36–39, DictReader field behavior and strict dialect. The codec adds an explicit presence flag and exact schema. No general RFC 4180 compliance claim for every accepted string.
- json — JSON Encoder and Decoder — Python 3.12 · Actually read official 3.12 reference Basic Usage: ensure_ascii, allow_nan, separators, sort_keys, loads object_pairs_hook and parse_constant. Rechecked both hook definitions for this chapter. The protocol deliberately rejects duplicate members, numeric readings and nonstandard constants beyond default parser behavior.
- decimal — Decimal Fixed-point and Floating-point Arithmetic — Python 3.12 · Actually read Introduction and Quick-start: immutable sign/coefficient/exponent and significance, exact construction from strings versus already-rounded floats, context affecting arithmetic rather than digit retention; FAQ lines 1472–1488 explains exponent removal preserving value but losing significance. Page displayed 3.12.13.
- RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format · Actually opened RFC URL, redirected to the RFC Editor info page containing the full standard. Read December 2017 header; sections 4–6 on unique names, array order and number interoperability; section 8.2 on unpaired surrogates, plus parser limits. The article does not claim JSON grammar mandates arbitrary-precision decoding or forbids every extension at the parser level.
- csv — CSV File Reading and Writing — Python 3.12 · Root independently read official writer None-to-empty conversion at line 39 and newline convention around line 43; inspected strict reader, exact four-field header, explicit presence flag and unchanged parser limit in the authored program.
- json — JSON Encoder and Decoder — Python 3.12 · Root independently read object_pairs_hook, parse_float, parse_int and parse_constant at lines 157–160. Hook runs on ordered member pairs, allowing duplicates to be rejected before a dict loses them; numerical readings remain protocol strings.
- decimal — Decimal Fixed-point and Floating-point Arithmetic — Python 3.12 · Root independently read construction behavior and exact float conversion lines 43–53. Reviewed fixed-point value preservation separately from exponent/significance metadata, conversion limits and arithmetic context.
- RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format · Root independently read unique-name/interoperability discussion lines 344–367 and number precision limits lines 429–439. The stricter application schema is distinguished from permissive parser behavior and from JSON syntax alone.
相关主题