【问题标题】:How to prettify JSON.stringify() partially?如何部分美化 JSON.stringify()?
【发布时间】:2021-01-16 23:43:07
【问题描述】:

用户可以从我们的应用程序中下载 JSON 文件,我想对其进行美化以便于调试,而不是全部在一行中。然而,即使缩进只是一个制表符或空格,这也会使文件大小增加近 40%。

作为妥协,我想排除所有值,例如美化的关键“大”,像这样:

{
 "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"}
}

我尝试使用 JSON.stringify 的replacer parameter 来解决这个问题:

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

但是“大”键的值最终被转义:

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>

如何防止这种转义发生或以其他方式在 JavaScript 中部分美化 JSON?

【问题讨论】:

  • "但是这会使文件大小增加近 40%" 这真的是个问题吗?数据不会通过网络,因为它都包含在客户端上,所以它不会真正花费更多时间来传输,或者占用更多带宽,或者以任何方式影响用户的数据上限(如果有的话) )。最多,它会在磁盘上占用更多空间,但除非您的 .json 文件占用数百兆字节您生成成千上万个文件,否则我认为驱动器空间不应该成为问题。
  • 除了@VLAZ所说的:启用gzip压缩。这将有助于减少空白对您的无线文件大小的影响。
  • @RickN 是的,这会有所帮助。事实上,它很可能已经生效了——大多数情况下 gzipping 是默认启用的。但是,由于此数据不会从服务器传输到客户端,因此不会被压缩。没必要,它已经客户端了——用户的机器会产生数据,然后用户会“下载”这些数据——基本上它会从RAM保存到磁盘。
  • 我认为你必须自己实现字符串化。有一些解决方法(例如用随机 5 个字符替换密钥,然后用压缩的 JSON 替换表示),但我认为它们很难看。
  • 您对我现在已删除的答案的评论是对的,内部引号使这种方式比看起来更难,以至于将您的 d 字符串更改为某事可能是个好主意确实有这样的内部引号。

标签: javascript json stringify prettify


【解决方案1】:

每次您在对象(或对象的一部分)more than once 上调用 JSON.stringify 时,都会得到转义的语音标记。在这种情况下,在将内部 JSON.stringify 函数应用于替换函数之后,无法告诉外部 JSON.stringify 函数不要像对待任何其他字符串一样对待该实例。

所以,我认为如果您的目标是“部分”字符串化一个对象,您需要编写一个实现该对象的函数。对于这个问题,我建议如下:

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>

这里使用了递归函数,它循环遍历对象的键并将键值对附加到字符串中,处理不同的数据类型。如果在exclude 数组中找到key,则将其字符串化。

通过遍历键并在需要时有条件地应用JSON.stringify,您可以有效地避免上述问题。

我确信在自己编写 JSON 而不是使用内置函数时可能需要注意一些极端情况,但您可以调整类似的内容以满足您的特定需求。

编辑:更新答案以更好地考虑对象中的数组。

【讨论】:

  • 这会将数组转换为无效的关联结构,例如我真正的大对象中的["0": "myvalue"]。如果您想尝试使用数组,我在示例中添加了数组。
  • 您的更新完成了这项工作,现在完美运行,谢谢!
  • 我今天注意到空数组被写为']',所以我使用 Math.max() 在你的代码中修复了它。
  • 有道理,谢谢你这样做。我很高兴它仍然有用:)
猜你喜欢
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
  • 2020-04-05
  • 1970-01-01
  • 2011-02-18
  • 2015-07-14
  • 1970-01-01
相关资源
最近更新 更多