Como embelezar JSON.stringify () parcialmente?

Oct 01 2020

Os usuários podem baixar arquivos JSON de nosso aplicativo, que quero embelezar para facilitar a depuração do que se todos estivessem em uma linha. No entanto, isso aumenta o tamanho do arquivo em quase 40%, mesmo se o recuo for apenas uma única tabulação ou espaço.

Como um meio-termo, quero excluir todos os valores com, por exemplo, a chave "grande" da atenuação, como este:

{
 "small":
 {
  "a": 1,
  "b": 2,
  "large": {"a":1,"b":2,"c":3,"d":"the \"large\" object should not be prettified"} 
 },
  "large": {"a":1,"b":2,"c":3,"d":"the \"large\" object should not be prettified"}
}

Tentei resolver isso usando o parâmetro de substituição de JSON.stringify:

JSON.stringify(data,(key,value)=>key==="large"?JSON.stringify(data):value,'\t');

No entanto, os valores para as chaves "grandes" acabam escapados:

data = 
{
     "small":
     {
      "a": 1,
      "b": [2,3,4,5],
      "large": {"myarray":[1,2,3,4],"b":2,"c":3,"d":"the \"large\" object should not be prettified"} 
     },
      "large": {"a":1,"b":2,"c":3,"d":"the \"large\" object should not be prettified"}
    }
    
 const json =  JSON.stringify(data,(key,value)=>key==="large"?JSON.stringify(data):value,'\t');
 document.getElementById("json").innerText = json;
<html>
<body>
<pre id="json">
</pre>
</body>
</html>

Como posso evitar que esse escape aconteça ou, de outra forma, embelezar parcialmente o JSON em JavaScript?

Respostas

2 sbgib Oct 06 2020 at 16:00

Cada vez que você chama JSON.stringifyum objeto (ou parte de um objeto) mais de uma vez , você vai acabar com marcas de discurso de escape. Nesse caso, após a JSON.stringifyfunção interna ter sido aplicada dentro da função de substituição, não há como dizer à JSON.stringifyfunção externa para não tratar essa instância como faria com qualquer outra string.

Então, eu acho que se seu objetivo é 'parcialmente' stringificar um objeto, você precisa escrever uma função que implemente isso. Para este problema, sugiro algo assim:

data = {
  "small": {
    "a": 1,
    "b": [2, 3, 4, 5],
    "c": [2, {"test":"example"}, [4,4], 5],
    "large": {
      "myarray": [1, 2, 3, 4],
      "b": 2,
      "c": 3,
      "d": "the \"large\" object should not be prettified"
    }
  },
  "large": {
    "a": 1,
    "b": 2,
    "c": 3,
    "d": "the \"large\" object should not be prettified"
  }
}

function print(obj, exclude, space) {
  let recur = (obj, spacing, inarray) => {
    let txt = '';

    if (inarray) {
      if (Array.isArray(obj)) {        
        txt += '[';

        for(let i=0;i<obj.length;i++) {
          txt += recur(obj[i], spacing + space, true);
        };

        txt = txt.substr(0, Math.max(1,txt.length - 2)) + ']';
        
      } else if (typeof obj === 'object' && obj !== null) {
        txt += '{' + recur(obj, spacing + space, false) + '\n' + spacing + '}';
      } else if (typeof obj === 'string') {
        txt += obj.replaceAll(/\"/g, '\\"') + '"';
      } else {
        txt += obj;
      };
      
      return txt + ', ';
      
    } else {
      for (let key of Object.keys(obj)) {
        if (exclude.indexOf(key) !== -1) {
          txt += '\n' + spacing + '"' + key + '": ' + JSON.stringify(obj[key]);
        } else if (Array.isArray(obj[key])) {
          txt += '\n' + spacing + '"' + key + '": [';
          
          for(let i=0;i<obj[key].length;i++) {
            txt += recur(obj[key][i], spacing + space, true);
          };
          
          txt = txt.substr(0, Math.max(1,txt.length - 2)) + ']';
          
        } else if (typeof obj[key] === 'object' && obj[key] !== null) {
          txt += '\n' + spacing + '"' + key + '": {' + recur(obj[key], spacing + space, false) + '\n' + spacing + '}';
        } else if (typeof obj[key] === 'string') {
          txt += '\n' + spacing + '"' + key + '": "' + obj[key].replaceAll(/\"/g, '\\"') + '"';
        } else {
          txt += '\n' + spacing + '"' + key + '": ' + obj[key];
        };
        
        txt += ',';
      };
      
      return txt.substr(0, txt.length - 1);
    };

  };
  return (Array.isArray(obj) ? '[' + recur(obj, space, true) + '\n' + ']' : '{' + recur(obj, space, false) + '\n' + '}');
};

document.getElementById("json").innerText = print(data, ['large'], '\t');
<html>
<body>
  <pre id="json">
</pre>
</body>
</html>

Aqui, uma função recursiva é usada, que percorre as chaves de um objeto e anexa o par chave-valor a uma string, tratando de diferentes tipos de dados. Se keyfor encontrado na excludematriz, ele é estringificado.

Ao percorrer as chaves e aplicar condicionalmente JSON.stringifyonde necessário, você está efetivamente evitando o problema acima.

Tenho certeza de que pode haver casos extremos a serem observados ao escrever o JSON em vez de usar uma função integrada, mas você pode adaptar algo assim para atender às suas necessidades específicas.

EDIT: resposta atualizada para melhor considerar os arrays dentro do objeto.