当前位置: 首页 > 科技观察

分享使用JSON相关方法的五个小技巧

时间:2023-03-16 23:39:13 科技观察

1。格式化默认的字符串化器也会收缩JSON,看起来很难看',国家:'美国'}};console.log(JSON.stringify(user));//=>{"name":"John","age":30,"isAdmin":true,"friends":["Bob","Jane"],"address":{"city":"NewYork","country":"USA"}}JSON.stringify也有一个内置的格式化程序!console.log(JSON.stringify(user,null,2));//{//"name":"John",//"age":30,//"isAdmin":true,//"friends":[//"Bob",//"Jane"//],//"address":{//"city":"NewYork",//"country":"USA"//}//}(如果您想知道null是什么,我们稍后会谈到)在这个例子中,JSON格式是2个空格用于缩进。我们还可以为缩进指定自定义字符。console.log(JSON.stringify(user,null,'lol'));//{//lol"name":"John",//lol"age":30,//lol"isAdmin":true,//lol"friends":[//lolol"Bob",//lolol"Jane"//lol],//lol"address":{//lollol"city":"NewYork",//lollol"country":"USA"//lol}//}2.隐藏字符串化数据JSON.stringify第二个参数中的一些属性,这在很大程度上是未知的。它称为替换器,它是一个函数或数组,用于决定将哪些数据保留在输出中,哪些不保留。这是一个简单的示例,我们可以在其中隐藏密码用户。constuser={姓名:'John',密码:'12345',年龄:30};console.log(JSON.stringify(user,(key,value)=>{if(key==='password'){return;}returnvalue;}));这里是输出:{"name":"John","age":30}我们可以进一步重构:functionstripKeys(...keys){return(key,value)=>{if(keys.includes(key)){返回;}返回值;};}constuser={name:'John',password:'12345',age:30,gender:'male'};console.log(JSON.stringify(user,stripKeys('password','gender')))输出:{"name":"John","age":30}你也可以传递一个数组来只获取某些键:constuser={name:'John',password:'12345',age:30}console.log(JSON.stringify(user,['name','age']))输出同样的东西。这也适用于数组。如果你有一堆蛋糕:constcakes=[{name:'ChocolateCake',recipe:['Mixflour,sugar,cocoapowder,bakingpowder,eggs,vanilla,andbutter','Mixinmilk','在350度下烘烤1小时',//...],ingredients:['flour','sugar','cocoapowder','bakingpowder','eggs','vanilla','butter']},//大量的这些];我们可以很容易地做同样的事情,替换器将应用于每个蛋糕:constcakes=[{name:'ChocolateCake',recipe:['Mixflour,sugar,cocoapowder,bakingpowder,eggs,vanilla,andbutter','拌入牛奶','350度烘烤1小时',//...],ingredients:['面粉','糖','可可粉','泡打粉','鸡蛋','香草','黄油']},//大量的这些];console.log(JSON.stringify(cakes,['name']))我们得到这个:[{"name":"ChocolateCake"},{"name":"VanillaCake"},...]3。使用toJSON创建自定义输出格式如果一个对象实现了toJSON函数,JSON.stringify将使用它来对数据进行字符串化考虑:classFraction{constructor(n,d){this.numerator=n;this.denominator=d;}}console.log(JSON.stringify(newFraction(1,2)))这将输出{"numerator":1,"denominator":2}。但是如果我们想用字符串替换其中的1/2怎么办?进入toJSONclassFraction{constructor(n,d){this.numerator=n;this.denominator=d;}toJSON(){return`${this.numerator}/${this.denominator}`}}console.log(JSON.stringify(newFraction(1,2)))JSON.stringify遵循toJSON属性并输出“1/2"。4.恢复数据我们上面的乐谱示例运行良好。但是如果我们想要恢复数据呢?如果当我们再次解析JSON时分数会神奇地返回,那不是很酷吗?我们可以!进入复活者!类分数{constructor(n,d){this.numerator=n;this.denominator=d;}toJSON(){return`${this.numerator}/${this.denominator}`}staticfromJSON(key,value){if(typeofvalue==='string'){constparts=value.split('/').map(数字);如果(parts.length===2)returnnewFraction(parts);}返回值;}}constfraction=newFraction(1,2);conststringified=JSON.stringify(fraction);console.log(stringified);//"1/2"constrevived=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(newDate()))//=>'"2022-03-01T06:28:41.308Z"'要恢复日期,我们可以使用JSON.parse:functionreviveDate(key,value){constregex=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,}|)Z$/;if(typeofvalue==="string"&®ex.test(value)){returnnewDate(value);}返回值;}console.log(JSON.parse('"2022-03-01T06:28:41.308Z"',reviveDate))//=>2022年3月1日星期二06:28:41GMT-0700(太平洋夏令时)Time)5.使用Revivers隐藏数据和解析器一样,恢复器也可以用来隐藏数据。它的工作方式相同。这是一个例子:constuser=JSON.stringify({name:'John',password:'12345',age:30});console.log(JSON.parse(user,(key,value)=>{if(key==='password'){return;}returnvalue;}));这是输出:{name:'John',age:30}