Let’s 开始!JavaScript中的5个JSON秘密功能

2022-03-1019:30:22WEB前端开发Comments1,466 views字数 4102阅读模式
Let’s 开始!JavaScript中的5个JSON秘密功能
来源 | 大迁世界 (ID:qq449245885)

在开发中,我们会经常使用 JSON.stringify(object) 来序列化对象,但JSON.stringify方法除了了第一个参数外,还有其它参数可用,今天我们一起来看看这些参数是做啥的,Let's 开始。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

1. 格式化

默认的 JSON.stringify(object) 出来数据是一行字符串,这看起来很丑,如下所示:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

const user = {
  name: '小智',
  age: 30,
  isAdmin: true,
  friends: ['隔壁老王', '小可爱'],
  address: {
    city: '天上人间',
  },
}
console.log(JSON.stringify(user))
// {"name":"小智","age":30,"isAdmin":true,"friends":["隔壁老王","小可爱"],"address":{"city":"天上人间"}}

JSON.stringify也有一个内置的格式化器!文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

console.log(JSON.stringify(user, null, 2))

{
  "name": "小智", 
  "age": 30,      
  "isAdmin": true,
  "friends": [
    "隔壁老王",
    "小可爱"
  ],
  "address": {
    "city": "天上人间"
  }
}

(如果你想知道这个 null 是什么,我们以后再谈)。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

在这个例子中,JSON的格式化有2个空格的缩进。我们还可以指定一个自定义字符,用于缩进。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

console.log(JSON.stringify(user, null, '【二哈】'))

{
【二哈】"name": "小智",
【二哈】"age": 30,
【二哈】"isAdmin": true,
【二哈】"friends": [
【二哈】【二哈】"隔壁老王",
【二哈】【二哈】"小可爱"
【二哈】],
【二哈】"address": {
【二哈】【二哈】"city": "天上人间"
【二哈】}
}

2. 在序列化的数据中隐藏某些属性

JSON.stringify 还有一个很少有人知道的第二个参,称为 replacer,是一个函数或数组,决定哪些数据要保留在输出中,哪些不要。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

举例一,假如,我们想隐藏用户的密码字段,可以这么做:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

const user = {
  name: '小智',
  password: '12345',
  age: 30
};


console.log(JSON.stringify(user, (key, value) => {
  if (key === 'password') {
    return
  }
  return value
}))

输出:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

{"name":"小智","age":30}

我们可以进一步重构:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

function  stripKeys (...keys) {
  return (key, value) => {
    if (keys.includes(key)) return 
    return value
  }
}
const user = {
  name: '小智',
  password: '12345',
  age: 30,
  gender: '未知'
};


console.log(JSON.stringify(user, stripKeys('password', 'gender')))

输出:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

{"name":"小智","age":30}

你也可以传递一个数组:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

const user = {
  name: '小智',
  password: '12345',
  age: 30
}

console.log(JSON.stringify(user, ['name', 'age']))

输出:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

{"name":"小智","age":30}

最酷的是这对数组也有效,假设有如下的数组:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

const poetry = [
  {
    name: '小智',
    content: [
      '兴尽晚回舟,误入藕花深处。',
      '鬼畜,鬼畜,单身百年手速。',
      '起点太高,于是期待太多,奢求太过,所以永不满足。',
    ],
    tags: ['经典', '魔幻', '鬼才'],
  },
  {
    name: '王大志',
    content: [
      '君子无非就是有耐心的狼。',
      '信者,无需誓言,不信者,誓言亦无助。'
    ],
    tags: ['经典', '魔幻', '鬼才'],
  },
]

由于诗太过美丽,我想出名,最后输出就想打出输出关于名字的字段,那么也可以使用 JSON.stringify 来做:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

console.log(JSON.stringify(poetry, ['name']))

输出:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

[{"name":"小智"},{"name":"王大志"}]

漂亮!文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

3. 使用 toJSON 来创建自定义输出格式

如果一个对象实现了 toJSON 函数,JSON.stringify 将使用它来串化数据。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

考虑一下这个例子:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

class Fraction {
  constructor(n, d) {
    this.numerator = n;
    this.denominator = d;
  }
}

console.log(JSON.stringify(new Fraction(1, 2)))

输出:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

{"numerator":1,"denominator":2}

如果我们想让输出的结果是 1/2,那要怎么做呢?实现 toJSON 方法。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

class Fraction {
  constructor(n, d) {
    this.numerator = n;
    this.denominator = d;
  }

  toJSON() {
      return `${this.numerator}/${this.denominator}`
  }
}

console.log(JSON.stringify(new Fraction(1, 2)))

JSON.stringify 根据 toJSON 方法来解析,所以结果是 1/2文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

4. 恢复数据

继续上面的例子,如果我们想再次解析JSON时,分数会神奇被还原成原来的对象,这是不是很酷?我们可以这样做:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

class Fraction {
  constructor(n, d) {
    this.numerator = n;
    this.denominator = d;
  }

  toJSON() {
      return `${this.numerator}/${this.denominator}`
  }

  static fromJSON(key, value) {
    if (typeof value === 'string') {
        const parts = value.split('/').map(Number);
        if (parts.length === 2) return new Fraction(parts);
    }

    return value;
  }
}

const fraction = new Fraction(1, 2);
const stringified = JSON.stringify(fraction);
console.log(stringified);
// "1/2"
const revived = JSON.parse(stringified, Fraction.fromJSON);
console.log(revived);
// Fraction { numerator: 1, denominator: 2 }

我们可以向 JSON.parse 传递第二个参数来指定一个 reviver 函数。reviver 的工作是将字符串化的数据 "恢复"到它的原始形式。在这里,我们传递了一个reviver,它是 Fraction 类的静态方法 fromJSON文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

有趣的是:这个功能在内置的Date对象中使用。试着查一下 Date.prototype.toJSON文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

console.log(JSON.stringify(new Date()))
//=> '"2022-03-01T06:28:41.308Z"'

为了恢复日期,我们可以使用 JSON.parse文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

function reviveDate(key, value) {
    const regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,}|)Z$/;

    if (typeof value === "string" && regex.test(value)) {
        return new Date(value);
    }

    return value;
}
console.log(JSON.parse('"2022-03-01T06:28:41.308Z"', reviveDate))
//=> Tue Mar 01 2022 06:28:41 GMT-0700 (Pacific Daylight Time)

5.使用 revivers  隐藏数据

stringify 一样,parse也可以用来隐藏数据。它们工作方式是一样的:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

const user = JSON.stringify({
  name: '小智',
  password: '12345',
  age: 30,
})

console.log(
  JSON.parse(user, (key, value) => {
    if (key === 'password') return
    return value
  })
)

输出:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html

{ name: '小智', age: 30 }
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/23414.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/23414.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定