JavaScript 使用替换功能进行序列化
示例
replacer可以使用一个函数来过滤或转换要序列化的值。
const userRecords = [ {name: "Joe", points: 14.9, level: 31.5}, {name: "Jane", points: 35.5, level: 74.4}, {name: "Jacob", points: 18.5, level: 41.2}, {name: "Jessie", points: 15.1, level: 28.1}, ]; //删除名称和将整数舍入为整数以在共享之前匿名记录 const anonymousReport = JSON.stringify(userRecords, (key, value) => key === 'name' ? undefined : (typeof value === 'number' ? Math.floor(value) : value) );
这将产生以下字符串:
'[{"points":14,"level":31},{"points":35,"level":74},{"points":18,"level":41},{"points":15,"level":28}]'