审查 AI 生成的 JSON 入库代码:大标识符与精确小数的数据契约
让 AI 为 Node.js 项目生成 JSON 导入代码时,最危险的错误往往没有异常:订单标识符少了一位精度,小数金额被提前转成浮点数,随后又被格式化成一段看起来完全正常的文本。接口能返回成功,数据库也能写入,只有跨系统核对时才发现同一个业务对象已经换了身份。问题并不只在某一次类型转换,而在整条数据链路没有约定哪些字段必须原样保留、哪些字段允许计算,以及转换发生在哪个边界。
本文用一个小型入库记录讨论这种审查:id 是无符号整数形式的业务标识符,amount 是非负、固定两位小数的单价,qty 是有上限的数量。我们先定义线上的数据表示,再处理历史数字字段,最后把解析、校验、内部计算和输出串起来。这是一份面向 AI 生成代码的应用级评审案例,重点是让每一次转换都有边界,而不是再罗列一遍 reviver 参数。

九段代码互相独立,都只依赖 Node 内置断言模块;每段保存为对应的 .mjs 文件后,以 node --unhandled-rejections=strict 文件名.mjs 运行。本文在 Node v24.19.0 上逐段实测通过,包含 context.source 的运行时验证。Node 24 官方发布说明可用于确认这一主版本的引擎背景,但这里不把它误写成 source 参数首次出现的版本。若部署环境没有 source 能力,相关入口必须明确失败,不能偷偷退回精度已经损失的 value。
一、先定位损失发生在哪里,别让 BigInt 成为补救幻觉
JSON 数字是一段文本,JavaScript Number 是一种运行时表示;两者不能直接画等号。普通 JSON.parse 把数字交给 Number 表示之后,大标识符可能已被舍入。随后调用 BigInt、String 或再次 JSON.stringify,只能处理现有值,没有证据找回原来的数字。ECMAScript 的安全整数说明明确展示了相邻大整数可能映射到同一个 Number 的现象。
第一段测试故意保留一份错误链路。它不是可复制到生产里的修复方案,而是用来推翻 AI 评审中常见的说法:解析之后马上转 BigInt 就不会丢精度。测试同时加入一个很长的小数字面量,说明所谓精度问题并不限于整数位数。最重要的审查问题是:用于恢复的字符串究竟来自原始输入,还是来自已经舍入的 Number?
独立测试 1,保存为 01_precision_loss.mjs:
import assert from "node:assert/strict";
const text = '{"id":9007199254740993,"amount":0.10000000000000001}';
const record = JSON.parse(text);
assert.equal(record.id, 9007199254740992);
assert.equal(BigInt(record.id), 9007199254740992n);
assert.notEqual(BigInt(record.id), 9007199254740993n);
assert.equal(String(record.amount), "0.1");
assert.equal(JSON.stringify(record), '{"id":9007199254740992,"amount":0.1}');
console.log("01 PASS: parsing already lost the original digits");实际输出:
01 PASS: parsing already lost the original digits
二、新协议先规定带引号的标识符,再谈内部类型
新接口优先把标识符定义成字符串。本文选择一个明确的业务子集:只接收 ASCII 十进制数字,不允许正负号、不允许前导零,零本身有效,最多二十位,且不超过 uint64 上界。这个上界来自本案例的跨系统契约,不是 BigInt 本身的能力上限。返回值仍是字符串,BigInt 只在经过长度和词法检查后用于边界比较。
这种设计把身份和算术分开了。标识符通常需要相等比较、索引和传输,而不是加减;保留字符串也让数据库驱动、浏览器与日志系统拥有一致的表示。如果业务编号里的前导零有意义,应另建允许前导零的文本契约,绝不能在这里擅自 trim 或删除零。电话号码、邮编和带校验位的编码也不应因为看起来像数字就套用本例。
这里采用字符串不是任意偏好。RFC 8259 第六节提醒实现可能限制数字精度,并指出常见实现间能够可靠互通的整数范围。超过范围的标识符继续以 JSON number 传输,会把正确性押在每一个消费端的解析策略上。
独立测试 2,保存为 02_quoted_identifier.mjs:
import assert from "node:assert/strict";
function readId(value) {
if (typeof value !== "string" || value.length > 20 ||
!/^(0|[1-9][0-9]*)$/.test(value)) {
throw new TypeError("id must be a canonical decimal string");
}
if (BigInt(value) > 18446744073709551615n) {
throw new RangeError("id exceeds uint64");
}
return value;
}
assert.equal(readId("9007199254740993"), "9007199254740993");
assert.equal(readId("18446744073709551615"), "18446744073709551615");
assert.equal(readId("0"), "0");
for (const value of [42, null, "", "01", "+1", "-0", " 1", "1e3",
"1", "1\n", "18446744073709551616", "9".repeat(21)]) {
assert.throws(() => readId(value));
}
console.log("02 PASS: quoted identifiers retain their identity");实际输出:
02 PASS: quoted identifiers retain their identity
三、数量字段要检查原始写法,也要检查解析后的值
数量和标识符语义不同,可以使用 Number,但仍要声明范围和语法。本例允许零到一百万的普通十进制整数记号,不接受指数、负零或带小数点的写法。1e3 与 1000 在数学上相等,不代表它们在一个要求普通整数记号的协议里都合法;这是有意收紧的应用规则,而非 JSON 标准禁止指数。
只用 Number.isSafeInteger 也不够。一个带有很多小数位的原始值可能先被舍入成整数,然后顺利通过检查。因此这里同时检验 source 的词法与 value 的类型、整数安全性和业务上限。外层 JSON 空白是合法分隔,不属于数字记号本体,所以测试允许前后的空白,却拒绝字符串形式的数量。
ECMAScript 的 InternalizeJSONProperty 算法给出了 source 的生成条件。它提供的是对应原始值的源文本,不等于完整请求,也不是通用字段路径。下面只解析一个独立数量记号,避免把这个小函数伪装成已经完成整条记录校验的入口。
独立测试 3,保存为 03_quantity_lexeme.mjs:
import assert from "node:assert/strict";
function readQuantityToken(text) {
return JSON.parse(text, (key, value, context) => {
if (key !== "" || typeof value !== "number" ||
typeof context?.source !== "string" ||
!/^(0|[1-9][0-9]{0,6})$/.test(context.source) ||
!Number.isSafeInteger(value) || value > 1_000_000) {
throw new TypeError("qty must be an integer token from 0 to 1000000");
}
return value;
});
}
assert.equal(readQuantityToken("1000000"), 1_000_000);
assert.equal(readQuantityToken(" 0 \n"), 0);
for (const text of ["1e3", "1.0", "-0", "-1", "1000001", "1e400",
'"2"', "null", "[]", "{}", "true"]) {
assert.throws(() => readQuantityToken(text));
}
assert.equal(Number.isSafeInteger(JSON.parse("1.0000000000000001")), true);
assert.throws(() => readQuantityToken("1.0000000000000001"));
console.log("03 PASS: validate the token before accepting the value");实际输出:
03 PASS: validate the token before accepting the value
四、历史数字标识符只能从原始记号进入适配层
旧接口有时已经把大标识符发布成 JSON number,短期内无法整体改版。此时可以建设明确的兼容入口:先限制输入字节数,再读取 source,验证普通非负整数写法和位数,最后用 BigInt 比较业务上限,输出统一的标识符字符串。不能先调用 Number 再决定是否足够大,也不能把指数形式通过数值计算展开为整数。
适配层的意义是集中兼容成本,而不是永久接受两套含糊协议。应记录哪些来源仍在走旧入口,为迁移保留可观测性;新写入和下游输出则保持同一种字符串格式。示例只接收独立数字记号,且在拿不到 source 时抛错。若完整对象中还包含其他同名字段,必须按结构定位字段,不能仅凭 key 等于 id 就替换整棵对象树中的内容。
长度限制发生在 BigInt 构造之前,避免把一个巨大整数字符串先交给大整数运算再做校验。这个数字位数预算与业务上限共同工作:二十位并不自动意味着处于 uint64 范围,所以上界比较仍然必需。
独立测试 4,保存为 04_legacy_adapter.mjs:
import assert from "node:assert/strict";
function readLegacyIdToken(text) {
if (typeof text !== "string" || Buffer.byteLength(text, "utf8") > 128) {
throw new RangeError("legacy token is too large");
}
return JSON.parse(text, (key, value, context) => {
if (key !== "" || typeof value !== "number" ||
typeof context?.source !== "string") {
throw new TypeError("expected a numeric token with source access");
}
const source = context.source;
if (source.length > 20 || !/^(0|[1-9][0-9]*)$/.test(source)) {
throw new TypeError("unsupported identifier spelling");
}
if (BigInt(source) > 18446744073709551615n) {
throw new RangeError("id exceeds uint64");
}
return source;
});
}
assert.equal(readLegacyIdToken("9007199254740993"), "9007199254740993");
assert.equal(readLegacyIdToken("18446744073709551615"), "18446744073709551615");
for (const text of ["1e3", "1.0", "-0", "1e400", '"12"',
"18446744073709551616", "9".repeat(129)]) {
assert.throws(() => readLegacyIdToken(text));
}
console.log("04 PASS: the bounded legacy adapter reads original digits");实际输出:
04 PASS: the bounded legacy adapter reads original digits
五、精确小数采用字符串与定点整数,不经过 Number 中转
金额字段要求的是十进制精确性以及固定的小数位格式。本例明确选择两位小数,整数部分最多十二位,所有金额非负;合法输入如 12.30 和 0.00。这里没有推导任何真实货币都应使用两位小数,也没有替用户决定舍入规则。不同货币、计价单位、税率和计量场景必须使用自己的精度契约。
解析时先验证整个字符串,再分别处理整数部分和小数部分,得到以最小单位计数的 BigInt。这个顺序不会出现先乘以一百再四舍五入的浮点路径。保留 text 字段还能保留约定的小数位,内部 minor 字段则负责准确加减。两者意义不同:字符串是传输与呈现格式,整数是计算表示;需要时应通过明确函数互相转换。
多出来的小数位在此被拒绝,不会自动截断。若后来增加折扣、比例分摊或除法,应另行说明何时舍入、采用哪种规则、余数如何分配,并为这些规则写测试。精确存储不等于所有后续运算都会自动满足业务要求。
独立测试 5,保存为 05_exact_decimal.mjs:
import assert from "node:assert/strict";
function parseAmount(value) {
if (typeof value !== "string" || value.length > 15 ||
!/^(0|[1-9][0-9]{0,11})\.[0-9]{2}$/.test(value)) {
throw new TypeError("amount requires a bounded scale-2 string");
}
const [whole, fraction] = value.split(".");
return { text: value, minor: BigInt(whole) * 100n + BigInt(fraction) };
}
assert.deepEqual(parseAmount("12.30"), { text: "12.30", minor: 1230n });
assert.equal(parseAmount("999999999999.99").minor, 99999999999999n);
assert.equal(parseAmount("0.10").minor + parseAmount("0.20").minor, 30n);
for (const value of [0.1, "0.1", "1", "01.00", "1e2", "1.001",
"-0.00", " 1.00", "1.00\n", "1000000000000.00"]) {
assert.throws(() => parseAmount(value));
}
console.log("05 PASS: exact decimal text becomes exact minor units");实际输出:
05 PASS: exact decimal text becomes exact minor units
六、BigInt 不能悄悄变回 JSON number,输出也需要契约
输入边界正确不代表响应就安全。内部对象出现 BigInt 后,默认 JSON.stringify 会抛出 TypeError;官方序列化算法规定了这一行为。评审时看到全局修改 BigInt.prototype.toJSON,或把所有 BigInt 一律转成 Number 的替换器,应该追问它影响了哪些接口、哪些字段可能因此失真。
本例采用显式输出映射:id 保持字符串,qty 保持已经验证过的 Number,计算结果通过有范围检查的格式化函数成为两位小数字符串。输出字段一眼可查,内部 amountMinor 不会意外泄露成另一个协议字段。即使某种序列化能力可以输出未加引号的大数字,也不能保证下一跳普通解析器不会再次丢失精度。
总额计算可以超出单价范围,因此格式化函数再次检查输出上限。测试特意让超上限和负数失败,避免出现输入合法就永远无需检查结果的错觉。数量转成 BigInt 的前提,是它已经通过了安全整数和范围校验;真实复用时应把这个前置条件放在函数入口或受控的领域对象构造器中。
独立测试 6,保存为 06_output_contract.mjs:
import assert from "node:assert/strict";
function formatAmount(minor) {
if (typeof minor !== "bigint" || minor < 0n || minor > 99999999999999n) {
throw new RangeError("amount is outside the output contract");
}
return `${minor / 100n}.${String(minor % 100n).padStart(2, "0")}`;
}
const domain = { id: "9007199254740993", qty: 3, unitMinor: 1230n };
assert.throws(() => JSON.stringify(domain), TypeError);
const totalMinor = domain.unitMinor * BigInt(domain.qty);
const dto = {
id: domain.id,
qty: domain.qty,
total: formatAmount(totalMinor)
};
const wire = JSON.stringify(dto);
assert.equal(wire, '{"id":"9007199254740993","qty":3,"total":"36.90"}');
assert.deepEqual(JSON.parse(wire), dto);
assert.equal(formatAmount(0n), "0.00");
assert.throws(() => formatAmount(100000000000000n));
assert.throws(() => formatAmount(-1n));
console.log("06 PASS: explicit output mapping preserves the wire contract");实际输出:
06 PASS: explicit output mapping preserves the wire contract
七、别把宽松转换当校验:攻击样本应专门反驳 AI 的捷径
AI 生成的导入器常喜欢先做一次“方便处理”:去空白、Number 转换、parseInt 截取前缀,或者无差别调用 String。问题是这些操作会把错误输入转换成可接受值,让校验失去判断依据。空字符串、十六进制前缀、布尔值、尾随杂字符,都应该由字段契约决定如何处理,而不是由某个通用转换函数代替产品规则。
ECMAScript 的 StringToBigInt 规则覆盖了字符串到大整数的转换语法,但它不是本应用的标识符语法。下一段同时展示几种宽松转换和严格入口的拒绝行为。额外放入带自定义 toString 的对象,是为了验证复用到内部调用时不会触发用户对象的隐式转换;普通 JSON 文本本身不会携带可执行的 toString 函数。
测试越接近错误推理,越能帮助评审。仅有一个很大的正确数字,无法发现错误输入被“清洗”后落库的问题。除了边界值,还应测试错误类型、空白、前导零、超长字符串、负零和指数,让模型不能只凭几个正常示例推断规则。
独立测试 7,保存为 07_coercion_traps.mjs:
import assert from "node:assert/strict";
function strictId(value) {
if (typeof value !== "string" || value.length > 20 ||
!/^(0|[1-9][0-9]*)$/.test(value) ||
BigInt(value) > 18446744073709551615n) {
throw new TypeError("invalid id");
}
return value;
}
assert.equal(Number(""), 0);
assert.equal(Number(" 12 "), 12);
assert.equal(Number("0x10"), 16);
assert.equal(Number(true), 1);
assert.equal(parseInt("12oops", 10), 12);
assert.equal(BigInt(""), 0n);
assert.equal(BigInt("0x10"), 16n);
let conversions = 0;
const object = { toString() { conversions += 1; return "12"; } };
for (const value of ["", " 12 ", "0x10", true, "12oops", object]) {
assert.throws(() => strictId(value));
}
assert.equal(conversions, 0);
assert.throws(() => strictId("1\n"));
assert.throws(() => strictId("1\r\n"));
console.log("07 PASS: validation does not normalize malformed identifiers");实际输出:
07 PASS: validation does not normalize malformed identifiers
八、把字段规则组合成一次提交前的完整检查
下面将三种字段接入一个入口:原始文本先受字节预算约束,解析期间收集数字原始记号,解析后检查根结构与字段集合,再分别验证 id、amount、qty,最后才调用保存函数。numberSources 按持有字段的对象记录 source,而不是把所有名为 qty 的字段混在一个全局变量里;嵌套同名字段因此不会冒充顶层数量。
保存前构造一个新的冻结对象,也避免直接把不受信任对象整体展开进数据库参数。多余字段包括 __proto__ 在这里都被字段白名单拒绝;这不意味着 JSON.parse 本身会因为出现该字段就修改原型。拒绝原因是本接口只接受约定的三个字段。对于批量导入,应先校验整批或明确记录逐条失败的策略,不能让一部分数据已写入以后才发现下一条输入不合法。
本段 save 是同步测试接收器,只证明错误记录不会到达它,不声称提供数据库事务、幂等性、异步错误处理或网络请求流量限制。生产服务需要在 HTTP 接收阶段就限制字节数,并把异步写入纳入可等待、可回滚或可重试的流程。更重要的是,普通 JSON.parse 会覆盖重复键,本入口并不拒绝它们;要求拒绝重复键时,必须在进入本函数之前增加能报告重复成员的解析层,不能把它当成完整安全边界直接上线。
独立测试 8,保存为 08_ingest_pipeline.mjs:
import assert from "node:assert/strict";
function ingest(text, save) {
if (typeof text !== "string" || Buffer.byteLength(text, "utf8") > 4096) {
throw new RangeError("record exceeds the input byte budget");
}
const numberSources = new WeakMap();
const input = JSON.parse(text, function (key, value, context) {
if (typeof value === "number") {
if (typeof context?.source !== "string") {
throw new Error("JSON source access is required");
}
let fields = numberSources.get(this);
if (!fields) numberSources.set(this, fields = new Map());
fields.set(key, context.source);
}
return value;
});
if (input === null || typeof input !== "object" || Array.isArray(input) ||
Object.keys(input).sort().join(",") !== "amount,id,qty") {
throw new TypeError("expected exactly id, amount and qty");
}
const { id, amount, qty } = input;
if (typeof id !== "string" || id.length > 20 ||
!/^(0|[1-9][0-9]*)$/.test(id) || BigInt(id) > 18446744073709551615n) {
throw new TypeError("invalid id");
}
if (typeof amount !== "string" || amount.length > 15 ||
!/^(0|[1-9][0-9]{0,11})\.[0-9]{2}$/.test(amount)) {
throw new TypeError("invalid amount");
}
const qtySource = numberSources.get(input)?.get("qty");
if (typeof qty !== "number" || typeof qtySource !== "string" ||
!/^(0|[1-9][0-9]{0,6})$/.test(qtySource) ||
!Number.isSafeInteger(qty) || qty > 1_000_000) {
throw new TypeError("invalid qty");
}
const [whole, fraction] = amount.split(".");
const record = Object.freeze({
id, amount, qty,
amountMinor: BigInt(whole) * 100n + BigInt(fraction)
});
save(record); // Only a synchronous test sink; no database transaction implied.
return record;
}
const writes = [];
const good = '{"id":"9007199254740993","amount":"12.30","qty":2}';
const result = ingest(good, value => writes.push(value));
assert.equal(result.amountMinor, 1230n);
assert.equal(writes.length, 1);
const bad = [
good.replace('"9007199254740993"', "9007199254740993"),
good.replace('"12.30"', "12.30"),
good.replace('"qty":2', '"qty":2e0'),
good.replace('"qty":2', '"qty":{"qty":2}'),
good.replace('"qty":2', '"qty":1e400'),
good.replace('"qty":2', '"qty":-0'),
good.replace("}", ',"__proto__":{"x":1}}'),
"[]", "null", " ".repeat(4097)
];
for (const text of bad) assert.throws(() => ingest(text, value => writes.push(value)));
assert.equal(writes.length, 1);
console.log("08 PASS: invalid inputs never reach the synchronous sink");实际输出:
08 PASS: invalid inputs never reach the synchronous sink
九、往返测试不能证明一切,要把未覆盖的边界公开
最后一段对安全整数附近、uint64 上限和金额上限做二十组往返断言。它检查的是契约字段经过输出和再次解析之后,字符串内容与类型保持一致,而不是只比较打印出来的文本是否相似。特别是 12.30 的末尾零,也属于我们明确约定的线格式。
测试还固定了三个容易被遗漏的事实:重复成员通常只剩最后一个值,Infinity 在序列化时会变成 null,负零会写成零。重复键中的早先异常值甚至可能在业务校验之前被后一个合法值覆盖。RFC 8259 第四节讨论了成员名不唯一时的互操作问题;用普通 reviver 无法把已覆盖的重复成员完整找回来。
因此,第八段的成功条件应准确描述成:在该解析器保留下来的对象上满足字段契约。如果项目需要拒绝重复键、限制嵌套深度,或保留完整审计原文,应选用能够满足这些要求的解析与接收层,并独立测试。不要用正则替换整个 JSON 文本来给数字补引号,它会混淆字符串内容、转义字符与真正的数字记号。
独立测试 9,保存为 09_roundtrip_boundaries.mjs:
import assert from "node:assert/strict";
function roundTrip(id, amount) {
assert.equal(typeof id, "string");
assert.ok(id.length <= 20 && /^(0|[1-9][0-9]*)$/.test(id));
assert.ok(BigInt(id) <= 18446744073709551615n);
assert.equal(typeof amount, "string");
assert.ok(amount.length <= 15 && /^(0|[1-9][0-9]{0,11})\.[0-9]{2}$/.test(amount));
const dto = { id, amount };
assert.deepEqual(JSON.parse(JSON.stringify(dto)), dto);
}
for (const id of ["0", "9007199254740991", "9007199254740992",
"9007199254740993", "18446744073709551615"]) {
for (const amount of ["0.00", "0.10", "12.30", "999999999999.99"]) {
roundTrip(id, amount);
}
}
assert.equal(JSON.parse('{"qty":2,"qty":3}').qty, 3);
assert.equal(JSON.parse('{"qty":1e400,"qty":2}').qty, 2);
assert.equal(JSON.stringify({ x: Infinity }), '{"x":null}');
assert.equal(JSON.stringify({ x: -0 }), '{"x":0}');
console.log("09 PASS: 20 round trips; duplicate keys remain a parser limitation");实际输出:
09 PASS: 20 round trips; duplicate keys remain a parser limitation
给 AI 的评审结论:先约定表示,再证明转换
审查一段 AI 生成的 JSON 入库代码,可以沿数据路径提出六个问题:原始字节在哪里变成对象;字段语义是否写清;每一次数值转换是否先验证词法和长度;内部精确值如何计算;输出是否继续遵守相同协议;失败是否发生在任何不可逆副作用之前。每个答案都应该能指向一个边界或一条可执行测试,而不只是“用了 BigInt 所以安全”的解释。
在本案例里,最值得保留的决策并不是某个新 API:新标识符始终带引号,小数始终使用明确精度的字符串,数量才在有限范围里使用 Number;历史数字字段通过独立、受限的 source 适配器迁移;内部 BigInt 通过显式映射离开服务。这些决策减少了推测,使模型生成的代码更容易被人复核,也让接口变化可以被测试捕捉。
本文的九个测试构成可重复的起点,而不是通用金融组件。接入数据库时仍需验证列类型、驱动参数、序列化中间件与读取路径:若某一层又把字符串转换成浮点数,入口的努力仍会失效。最可靠的验收方式是选一个真实的大标识符和带尾随零的小数,贯穿请求、存储、读取与响应逐层比较,确认没有任何一站擅自改变它们的含义。

