ngx-json-viewer icon indicating copy to clipboard operation
ngx-json-viewer copied to clipboard

JSON.stringify(segment.value) is not very efficient for generating value preview

Open phplego opened this issue 2 years ago • 3 comments

It causes performance issues with big json data

phplego avatar Nov 25 '22 09:11 phplego

Thanks! feel free to create a PR for a better approach.

hivivo avatar Nov 29 '22 05:11 hivivo

I have created this pretty fast preview function. It breaks generation if limit is reached

function previewLimited(obj:any, limit = 100, stringsLimit = 10) {
  let result = '';

  if (typeof obj === 'string') {
    if(obj.length > stringsLimit)
      result += `"${obj.substring(0, stringsLimit)}…"`;
    else
      result += `"${obj}"`;
  } else if (typeof obj === 'boolean') {
    result += `${obj ? 'true' : 'false'}`;
  } else if (typeof obj === 'number') {
    result += `${obj}`;
  } else if (typeof obj === 'object'){
    const isArray = Array.isArray(obj)
    result += isArray ? `(${obj.length})[` : '{';
    for (const key in obj) {
      const value = obj[key];

      result += isArray ? '': `${key}: `;

      if(result.length >= limit)
        return result.substring(0, limit)

      result += previewLimited(value, limit - result.length);
      result += `, `;
    }
    if(result.endsWith(', '))
      result = result.slice(0, -2)
    result += isArray ? ']' : '}';
  }

  if(result.length >= limit)
    return result.substring(0, limit)

  return result;
}

phplego avatar Dec 03 '22 18:12 phplego

Pull request: #126

phplego avatar Dec 03 '22 18:12 phplego