有没有什么快速的方法可以减少网络传输时数据的字节数?
我将数据从服务器发送到浏览器,它占用了相当多的带宽
我的数据看起来像这样,但具有更多属性:
{
1: {width: 10.25, height: 30.75,},
2: {width: 7.5, height: 1.25,},
}
Json 编码
以 CSV 形式发送数据,这样您就无需将字段名称包含在每个项目的有效负载中。
如果您想要 JSON,您可以缩小对象属性并将缩小图与数据一起发送:
const obj = {
1: { width: 10.25, height: 30.75, },
2: { width: 7.5, height: 1.25, },
};
let charCode = 97;
const pack = obj => JSON.stringify(
Object.entries(obj).reduce((packed, [idx, item]) => {
packed.obj[idx] = Object.keys(item).reduce((obj, key) => {
obj[packed.map[key] ??= String.fromCharCode(charCode++)] = item[key];
return obj;
}, {});
return packed;
}, { obj: {}, map: {} })
);
const unpack = str => {
const { obj, map } = JSON.parse(str);
const inverted = Object.entries(map).reduce((inverted, [k, v]) => {
inverted[v] = k;
return inverted;
}, {});
return Object.entries(obj).reduce((obj, [idx, item]) => {
obj[idx] = Object.entries(item).reduce((item, [key, val]) => {
item[inverted[key]] = val;
return item;
}, {});
return obj;
}, {});
};
const packed = pack(obj);
console.log('PACKED:', packed);
const unpacked = unpack(packed);
console.log('UNPACKED', JSON.stringify(unpacked));