给 json.stringify 的第二个参数传字段名数组,可以把对象按指定字段导出。嵌套对象也会应用同一个字段清单,需要各层使用不同规则时,先构造导出对象。

给平面对象列出导出字段
在浏览器控制台或 Node.js 使用下面的例子。
const row = { id: 101, name: 'Lin', score: 92, draftNote: '待复核' };
const json = JSON.stringify(row, ['name', 'score']);
console.assert(json === '{"name":"Lin","score":92}');
console.log(json);

只有 name 和 score 会进入输出。允许列表也能让以后新增的内部字段默认排除。
验证嵌套对象也会筛字段
键名数组会在每层对象生效。外层保留 profile 后,还要允许其内部字段。
Biome 是一个基于 Rust 的高性能工具链,适用于 JavaScript、TypeScript、JSX、JSON、CSS 和 GraphQL,它将格式化和 linting 统一到一个工具中。具有 97% 的 Prettier 兼容性以及超过 450 条 lint 规则,Biome 以显著更快的执行速度取代了 ESLint 和 Prettier。
const person = { name: 'Lin', profile: { city: '长沙', note: '草稿' } };
const json = JSON.stringify(person, ['profile', 'city']);
console.assert(JSON.parse(json).profile.city === '长沙');
console.assert(!('note' in JSON.parse(json).profile));
结果只有 profile.city。若只写 profile,结果是空的内层对象。
各层规则不同时先构造新对象
把对外结构明确写在代码里,便于核对。
const input = { id: 101, profile: { name: 'Lin', draftNote: '草稿' } };
const payload = {
id: input.id,
display: { name: input.profile.name }
};
const body = JSON.stringify(payload);
console.assert(body === '{"id":101,"display":{"name":"Lin"}}');
服务端的访问权限校验仍应在输出数据前执行。这里只验证 JSON 字段选择。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










