简体   繁体   English

懒惰的 JSON.stringify

[英]Lazy JSON.stringify

Problem --问题 -

users use a library, to send logs to the backend.用户使用库,将日志发送到后端。 The library has a circular buffer, so that there are no more then a few hundred elements.该库有一个循环缓冲区,因此不会超过几百个元素。

However, we don't control the size of the elements that are sent, so it's possible to have payloads > 10mb.但是,我们无法控制发送的元素的大小,因此有效载荷可能大于 10mb。

I'd like to reduce this, by asserting a limit on the overall size of the payload.我想通过对有效负载的整体大小进行限制来减少这种情况。

However, I don't think there is a way for me to get the size of objects.但是,我认为没有办法获得对象的size

What I'm thinking is a sort of lazy JSON.stringify我在想的是一种懒惰的 JSON.stringify

var res = "[";
messages.forEach(m => {
  if (res.length < MAX_SIZE) {
    res += JSON.stringify(m);
    res += ",";
  })
});
res += "]"

Is there a better way?有没有更好的办法?

For posterity, it would have been simpler to do this kind of filtering before the JSON.stringify call.对于后代,在 JSON.stringify 调用之前进行这种过滤会更简单。

ie: go over messages , replace items that are too large with "..too large.." , and then stringify.即:检查messages ,用"..too large.."替换太大的项目,然后字符串化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM