Data formats: preserve types, missingness and decimal values
数据格式与序列化
Define one record protocol, round-trip it through CSV and JSON, and reject silent changes of meaning.
data-formatsThe file opens, but the meaning may already have changed
A measurement archive exports three records. One ID is 0007, one reading is missing, one note is empty, and another note contains a comma, a line break and quotation marks. A decimal reading is 9007199254740993.01.
A careless import can turn the ID into 7, treat the missing reading as zero, split the note into several records or round the decimal. The file may still be syntactically valid. The problem is that serialization has not preserved the application’s data model.
We will define one small record protocol with CSV and JSON encodings. Both must preserve record order, exact ID and note strings, missingness and decimal numerical values. This is a codec for a stated schema, not a universal exporter for arbitrary Python objects.
Define types and missingness before choosing punctuation
The logical record
A record contains a nonempty string ID, a reading that is either a finite Decimal or None, and a string note that may be empty. IDs are unique within the collection. None means “no reading supplied”; it is different from decimal zero and from an empty text note.
A finite decimal represents a sign, coefficient and exponent:
The codec stores the reading as fixed-point decimal text. Parsing that text into Decimal preserves its numerical value without first passing through binary floating point. It does not promise to preserve every original exponent/significance annotation: Decimal('1E+3') becomes the text 1000. If scale itself is meaningful metadata, give it a separate field or encode the decimal tuple explicitly. Python’s decimal reference distinguishes numerical value, significance and arithmetic context.
Two representations of the same record
| Logical field | CSV protocol | JSON protocol |
|---|---|---|
| ID | id text column | id string member |
| Present reading | reading_present is 1; reading holds decimal text | reading is a decimal string |
| Missing reading | reading_present is 0; reading must be empty | reading is null |
| Note | Text, with CSV quoting when needed | String, with JSON escapes when needed |
| Version | This exact four-column header is the version-1 CSV contract | Top-level integer schema equals 1 |
CSV does not supply this field typing by itself. The Python CSV documentation describes its ordinary string-returning parser and quoting rules; the application adds the presence flag and schema. Writing None directly through a CSV writer would produce an empty field and lose the distinction unless the surrounding protocol restores it.
JSON has a null value and distinguishes strings from numbers, but its number syntax does not force every consumer to use arbitrary precision. RFC 8259 discusses numeric interoperability limits and the unpredictable handling of duplicate object names. Our protocol uses decimal strings, rejects numeric readings and duplicate members, and requires every declared field. A missing reading key is a malformed record; an explicit null is a valid missing reading.
Round trips need an explicit equivalence relation
For valid records, the requirement is:
Here equivalence means the same ordered records, string contents, missing-value positions and exact decimal numerical values. It does not require identical original file bytes, quoting choices, JSON member order or Decimal exponent metadata. This distinction matters when deciding whether a round-trip test is strong enough.
Checking only a round trip is insufficient: an encoder and decoder can share the same mistake. Inspect the wire representation independently, test hand-authored input and compare numeric values with a separate exact representation.
A schema-aware CSV and JSON codec
The Python 3.12 program uses only the standard library and returns text or tuples of Record objects. To write a file, explicitly encode the returned text as UTF-8; when using a text file with the CSV reader/writer, use newline=''. The code’s StringIO already applies that newline convention.
Collections must be lists or tuples of plain Record instances; an empty collection is valid. IDs and notes must be UTF-8-encodable strings of at most 4096 characters. The CSV functions require the interpreter’s parser field limit to be at least 4096 and do not change that global setting. Reading values must be finite Decimal instances with at most 80 coefficient digits, exponent between −20 and 20, and fixed-point output no longer than 80 characters. These teaching limits bound individual numeric conversions. On the wire, decimal text permits an optional minus sign, ordinary integer digits and an optional fractional part; it does not permit a plus sign, exponent notation, extra leading zeros or whitespace.
Both decoders validate every record. Unknown or missing JSON fields, wrong types, duplicate IDs, inconsistent CSV presence flags and unsupported versions fail. JSON duplicate keys and nonstandard NaN/Infinity literals are rejected during parsing. Ordinary syntax/domain errors raise ValueError; this is not a streaming parser or a resource-isolation layer for unlimited input.
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)
Output:
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
The ID 0007 remains text. The missing reading remains None, while -0.00 remains a present zero. The quoted note survives both encodings, including its embedded newline. The displayed CSV uses Python repr, so visible \r\n sequences describe actual record-ending characters in the returned string.
The decimal also survives both codecs. The separate float conversion fails the exact-value comparison because information is lost before decoding could help. Constructing a Decimal from an already-rounded float preserves that float’s value, not the original decimal text. Decimal construction behavior
For a valid collection, let B be the total text size processed or produced and N the record count. With bounded numeric fields and expected dictionary/set operations, each codec uses O(B+N+1) work and O(B+N+1) memory, including its full text and record representation. Record order is retained; the program does not sort the collection. It materializes the entire input/output rather than claiming streaming memory usage.
A format does not supply the whole protocol
The schema still needs external meaning. These records do not specify measurement units, collection time, calibration version or why a reading is missing. Add those fields when the application needs them, and define a migration rather than silently changing version 1. Rejecting unknown fields prevents an older reader from pretending to understand a newer record, but also means compatibility changes must be intentional.
Opening CSV in a spreadsheet can invoke type inference that ignores this protocol. A leading-zero ID or high-precision reading is safe only if the consumer keeps the declared text types. Similarly, another JSON consumer must know that reading is a decimal string, not ordinary descriptive text. The agreement between producer and consumer is what preserves meaning.
Decimal storage avoids binary conversion at the interchange boundary; it does not make later arithmetic exact under every context. Division or multiplication may still round according to the configured precision. This codec performs no reading arithmetic. Its fixed-point representation preserves value, while applications that require significant-place metadata need a richer schema.
For large tables, a row-oriented text format may be expensive to parse and awkward for selective column access. For arrays, shape and dtype also need representation. Those are reasons to evaluate typed binary formats for the actual workload, not to assume that changing a file extension solves missingness, units or compatibility.
Look for information that can disappear
- Why does the CSV protocol need
reading_presentif it already has a reading column?
Answer: An empty field alone has no universal missing-value meaning. The explicit flag distinguishes a missing reading from a present decimal value and lets the decoder reject contradictory input, such as flag 0 with payload 12.5. Empty notes remain independent text values.
- A consumer converts the decimal string to a float, then constructs
Decimalfrom that float. Has it followed the precision contract?
Answer: No. The binary conversion may discard decimal information. The consumer should construct its exact decimal representation directly from the string. A later exact conversion cannot infer digits already lost.
- Should
{"id":"0007","id":"0008"}be accepted by keeping the last ID?
Answer: Not under this protocol. Duplicate member names are rejected, so records do not depend on a parser’s first/last-value policy. This object also lacks required fields; either defect is sufficient to reject it.
Decimal('1E+3')returns asDecimal('1000'). Has the round-trip contract failed? What if the original exponent carries measurement significance?
Answer: Numerical value is preserved, so this contract succeeds. It deliberately does not preserve all exponent/significance metadata. If that metadata matters, store a scale or the sign/coefficient/exponent tuple in a revised schema and test that stronger equivalence.
Standards describe syntax; applications choose semantics
RFC 8259 defines JSON’s value types and documents interoperability issues. The Python JSON reference exposes parser hooks and serialization options; these allow the stricter duplicate-key and numeric policies used here. Neither source defines what a measurement ID or missing reading means.
The CSV reference explains quoting and newline handling, while the decimal reference explains numerical values and significance. Read them alongside the application schema. Continue with data frames for column-level operations and experiment reproducibility for tying a stored artifact to its producing code and inputs.
Make a prediction, then check
The schema requires a reading key whose value may be null. Which input represents a valid missing reading?
Learning objectives
- Specify record types and distinguish missing, zero, empty text and absent keys.
- Preserve decimal numerical values and string identities through CSV and JSON.
- Test a semantic round trip independently of shared encoder/decoder assumptions.
Prerequisites & connections
Explore related knowledge →References
- 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
Version1 · Editorial status: Recorded technical checks completed
View technical check record (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.
- Seven tests passed under CPython 3.12.12 and 3.12.4. Handwritten CSV/JSON fixtures verify exact emitted text and independent decoding. Eight records have wire values checked by integer-digit Fraction parsing, separately from Decimal decoding; IDs, notes, presence markers, nulls and types are checked too.
- Checked 4096-character field boundaries, the required CSV parser limit without changing it, empty collections, both codecs, re-encoding, 80-character numeric boundaries, exponent metadata loss with value preservation, precision-two context, Unicode/quotes/newlines, duplicate and escape-equivalent JSON keys, invalid presence flags, wrong types, unsupported schemas and nonfinite values. Seven stdout lines reproduced.
- Complete original paired Python, two matching displays, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML passed. Humanizer reread; AI author checks only, written pending independent review. Full in-memory codec, no universal object serializer or streaming claim. Draft files only.
- Root fully read both articles and complete codec, checked the two formulas, exact round-trip equivalence, four answers and six anchors. Seven author tests and strict MDX/KaTeX/React HTML rerun under CPython 3.12.4 pass. Frozen five-file hashes match; no revisions required.
- Reviewed independent handwritten wire fixtures and integer/Fraction numeric checks already present in the author tests; no duplicate reference was added. Inspected schema/type rejection, explicit missingness, leading-zero identity preservation, UTF-8 and CSV field limits, Decimal encoder/decoder domain closure and significance loss. Claimed expected hash-operation cost and full materialization match the bounded protocol.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- 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.
Related topics