* 1、格式化
默认的字符串化器还会缩小 JSON,看起来很难看
const user = {name: 'John',age: 30,isAdmin: true,friends: ['Bob', 'Jane'],address: {city: 'New York',country: 'USA'}};console.log(JSON.stringify(user));//=> {"name":"John","age":30,"isAdmin":true,"friends":["Bob","Jane"],"address":{"city":"New York","country":"USA"}}
JSON.stringify也有一个内置的格式化程序!
console.log(JSON.stringify(user, null, 2));// {// "name": "John",// "age": 30,// "isAdmin": true,// "friends": [// "Bob",// "Jane"// ],// "address": {// "city": "New York",// "country": "USA"// }// }
(如果你想知道那个 null 是什么,我们稍后会谈到)
在此示例中,JSON 格式为 2 个缩进空格。
我们还可以指定用于缩进的自定义字符。
console.log(JSON.stringify(user, null, 'lol'));// {// lol"name": "John",// lol"age": 30,// lol"isAdmin": true,// lol"friends": [// lollol"Bob",// lollol"Jane"// lol],// lol"address": {// lollol"city": "New York",// lollol"country": "USA"// lol}// }
* 2、隐藏字符串化数据中的某些属性
JSON.stringify第二个参数,这在很大程度上是未知的。它被称为replacer,它是一个函数或数组,用于决定哪些数据保留在输出中,哪些不保留。
这是一个简单的示例,我们可以在其中隐藏password用户。
const user = {name: 'John',password: '12345',age: 30};console.log(JSON.stringify(user, (key, value) => {if (key === 'password') {return;}return value;}));
这是输出:
{“name”:”John”,”age”:30}
我们可以进一步重构:
function stripKeys(...keys) {return (key, value) => {if (keys.includes(key)) {return;}return value;};}const user = {name: 'John',password: '12345',age: 30,gender: 'male'};console.log(JSON.stringify(user, stripKeys('password', 'gender')))
输出:
{“name”:”John”,”age”:30}
还可以传递一个数组来仅获取某些键:
const user = {name: 'John',password: '12345',age: 30}console.log(JSON.stringify(user, ['name', 'age']))
输出相同的东西。
这也适用于数组。如果你有一大堆蛋糕:
const cakes = [{name: 'Chocolate Cake',recipe: ['Mix flour, sugar, cocoa powder, baking powder, eggs, vanilla, and butter','Mix in milk','Bake at 350 degrees for 1 hour',// ...],ingredients: ['flour', 'sugar', 'cocoa powder', 'baking powder', 'eggs', 'vanilla', 'butter']},// tons of these];
我们可以轻松地做同样的事情,并且替换器将应用于每个蛋糕:
const cakes = [{name: 'Chocolate Cake',recipe: ['Mix flour, sugar, cocoa powder, baking powder, eggs, vanilla, and butter','Mix in milk','Bake at 350 degrees for 1 hour',// ...],ingredients: ['flour', 'sugar', 'cocoa powder', 'baking powder', 'eggs', 'vanilla', 'butter']},// tons of these];console.log(JSON.stringify(cakes, ['name']))
我们得到这个:
[{“name”:”Chocolate Cake”},{“name”:”Vanilla Cake”},…]
3、使用toJSON创建自定义输出格式
如果一个对象实现了该toJSON函数,JSON.stringify将使用它来对数据进行字符串化。
考虑一下:
class Fraction {constructor(n, d) {this.numerator = n;this.denominator = d;}}console.log(JSON.stringify(new Fraction(1, 2)))
这将输出{“numerator”:1,”denominator”:2}. 但是如果我们想用一个字符串替换它1/2呢?
进入toJSON
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”。
4、恢复数据
我们上面的分数示例效果很好。但是如果我们想恢复数据呢?当我们再次解析 JSON 时,如果分数能神奇地返回,那不是很酷吗?我们可以!
进入复活者!
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,它是类的静态fromJSON属性Fraction。
在这种情况下,reviver 检查该值是否是一个有效的分数,如果是,它会创建一个新Fraction对象并返回它。
有趣的事实:此功能用于内置的 Date 对象。尝试查找Date.prototype.toJSON
这就是为什么它有效:
console.log(JSON.stringify(new Date()))//=> '"2022-03-01T06:28:41.308Z"'
要恢复日期,我们可以使用JSON.parse:
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隐藏数据
与解析器一样,恢复器也可用于隐藏数据。它以相同的方式工作。
这是一个例子:
const user = JSON.stringify({name: 'John',password: '12345',age: 30});console.log(JSON.parse(user, (key, value) => {if (key === 'password') {return;}return value;}));
这是输出:
{ name: ‘John’, age: 30 }
