JSON.stringify() 的若干用法

JSON.stringify() 的用法

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JSON.stringify() 的用法</title>
</head>

<body>
  <script>
    var miKe = {
      'name': 'miKe',
      'age': 88,
      'sex': 'men',
      'work': 'doctor'
    }
    console.log(miKe)

    // 用法1:对象转字符串
    console.log(JSON.stringify(miKe))

    // 用法2:第二个参数(数组)。可以让我们重写代码并查看结果。
    console.log(JSON.stringify(miKe, ['work']))   // {"work":"doctor"}  (输出结果为string类型)

    // 用法3:第二个参数(函数)---它根据函数中写入的逻辑来计算每个键值对。如果返回 undefined,则不会打印键值对。
    var result = JSON.stringify(miKe, (key, value) => {
      if (typeof value == 'string') {
        return undefined;
      }
      return value;
    })
    console.log(result)  // {"age":88} (输出结果为string类型)
    // 这里只有 age 被打印出来,因为函数判断 typeOf 为 String 的值返回 undefined。


    // 用法4:第三个参数为数字。第三个参数控制最后一个字符串的间距。如果参数是一个数字,则字符串化中的每个级别都将缩进这个数量的空格字符。
    var thirdParam = JSON.stringify(miKe, null, 2)
    console.log(thirdParam)


    // 用法5:第三个参数为字符串。如果第三个参数是 string,那么将使用它来代替上面显示的空格字符。
    var thirdParamString = JSON.stringify(miKe, null, '**')
    console.log(thirdParamString)


    // 用法6:toJSON 方法。它可以作为任意对象的属性。JSON.stringify 返回这个函数的结果并对其进行序列化,而不是将整个对象转换为字符串。
    var maraya = {
      'bigName': 'maraya',
      'smallName': 'KiMi',
      'sex': 'girl',
      'work': 'student',
      toJSON() {
        return {
          allName: `${this.bigName}${this.smallName}`
        }
      }
    }
    console.log(maraya)
    console.log(JSON.stringify(maraya))  //  {"allName":"maraya 和 KiMi"}    (输出结果为string类型)


    // 用法7:存储 localStorage 对象。假如,你想存储用户创建的一个对象,并且,即使在浏览器被关闭后仍能恢复该对象。请看下例子:
    // 创建一个示例数据
    var session = {
      'screens': [],
      'state': true
    };
    session.screens.push({ "name": "screenA", "width": 450, "height": 250 });
    session.screens.push({ "name": "screenB", "width": 650, "height": 350 });
    session.screens.push({ "name": "screenC", "width": 750, "height": 120 });
    session.screens.push({ "name": "screenD", "width": 250, "height": 60 });
    session.screens.push({ "name": "screenE", "width": 390, "height": 120 });
    session.screens.push({ "name": "screenF", "width": 1240, "height": 650 });

    // 使用 JSON.stringify 转换为 JSON 字符串
    // 然后使用 localStorage 保存在 session 名称里
    localStorage.setItem('session', JSON.stringify(session));

    // 然后是如何转换通过 JSON.stringify 生成的字符串,该字符串以 JSON 格式保存在 localStorage 里
    var restoredSession = JSON.parse(localStorage.getItem('session'));

    // 现在 restoredSession 包含了保存在 localStorage 里的对象
    console.log(restoredSession);


    // 用法8:数组去重
    function unique(arr) {
      let unique = {};
      arr.forEach(function (item) {
        //调整属性顺序
        var newData = {};
        Object.keys(item).sort().map(key => {
          newData[key] = item[key]
        })
        unique[JSON.stringify(newData)] = item; //键名不会重复
      })
      arr = Object.keys(unique).map(function (u) {
        //Object.keys()返回对象的所有键值组成的数组,map方法是一个遍历方法,返回遍历结果组成的数组.将unique对象的键名还原成对象数组
        return JSON.parse(u);
      })
      return arr;
    }
    var arr = [{ x: 1, y: 2 }, { y: 2, x: 1 }]
    console.log(unique(arr))   // [{x: 1, y: 2}] 


    // 用法9:stringify 函数第二个参数: 解决对象属性的顺序问题
    function uniq(arr) {
      let unique = {};
      arr.forEach(function (item) {
        unique[JSON.stringify(item, ['name', 'author'])] = item;
      })
      arr = Object.keys(unique).map(function (u) {
        //Object.keys()返回对象的所有键值组成的数组,map方法是一个遍历方法,返回遍历结果组成的数组.将unique对象的键名还原成对象数组
        return JSON.parse(u);
      })
      return arr;
    }
    var ar = [{ 'author': "ABC", 'name': 'ermao' }, { 'name': 'damao', 'author': "ABC" }, { 'author': "ABC", 'name': 'ermao' }]
    console.log(uniq(ar))


    // 用法10:JSON.stringify()与 JSON.parse()来实现深拷贝
    function deepClone(data) {
      let _data = JSON.stringify(data),
        dataClone = JSON.parse(_data);
      return dataClone;
    };
    //测试
    let arrr = [1, 2, 3],
      _arr = deepClone(arrr);
    arrr[0] = 2;
    console.log(arrr, _arr)//[2,2,3]  [1,2,3]


    // 用法11:判断数组是否包含某对象,或者判断对象是否相等。
    //判断数组是否包含某对象
    let data = [
      { name: '小明' },
      { name: '小花' },
      { name: '胖墩' },
    ],
      val = { name: '小花' };
    console.log(JSON.stringify(data).indexOf(JSON.stringify(val)) !== -1); // true

    //判断两数组/对象是否相等
    let a = [1, 2, 3],
      b = [1, 2, 3];
    console.log(JSON.stringify(a) === JSON.stringify(b)); // true

  </script>
</body>

</html>

欢迎评论与指正!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值