JS 将 json 对象转成字符串并保留格式 - JSON.stringify()

  • JSON.stringify(value, replacer, space)

    • value:将要序列化成一个 JSON 字符串的值。

    • replacer(可选):如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中;如果该参数为 null 或者未提供,则对象所有的属性都会被序列化。

    • space(可选):指定缩进用的空白字符串,用于美化输出(pretty-print);如果参数是个数字,它代表有多少的空格;上限为 10。该值若小于 1,则意味着没有空格;如果该参数为字符串(字符串的前十个字母),该字符串将被作为空格;如果该参数没有提供(或为 null)将没有空格。

  • 细节注意:如果使用数字之类的无效,可以尝试字符串。例如 全角空格,在有些小程序或者特殊项目中可以通过这个进行解决。

  • 案例效果

    <script>
      const json = {
          
          
        "key1": 123,
        key2: "测试",
        key3: 'asldjlaskjd',
        key4: 'https://www.baidu.com/'
      }
      // 普通转换
      console.log(JSON.stringify(json), '=======>1')
      // 缩进 2 个
      console.log(JSON.stringify(json, null, 2), '=======>2')
      // 缩进 4 个
      console.log(JSON.stringify(json, null, 4), '=======>3')
      // 好像是缩进了 4 个
      console.log(JSON.stringify(json, null, '\t'), '=======>4')
      // 前面以 test 字符串为缩进
      console.log(JSON.stringify(json, null, 'test'), '=======>5')
      // 前面以 2个普通空格 字符串为缩进
      console.log(JSON.stringify(json, null, '  '), '=======>6')
      // 前面以 2个全角空格 字符串为缩进
      console.log(JSON.stringify(json, null, '  '), '=======>7')
      // 前面缩进换成换行符
      console.log(JSON.stringify(json, null, '\n'), '=======>8')
    </script>
    

    image.png

猜你喜欢

转载自blog.csdn.net/zz00008888/article/details/132293476
今日推荐