朋友们,美好的一天!在这篇简短的文章中,我想告诉您一些JSON.stringify()很少使用的功能。它们可能对您有用。JSON.stringify()通常在调试期间用于将对象或常规字符串转换为JSON格式的字符串。但是如何使用此方法,我们可以绕开toString()吗?让我们尝试去做。
const user = {
name: 'Harry Heman',
age: 29,
job: 'developer'
}
console.log(user.toString())
[object Object]并不是我们想要看到的,是吗?不要问为什么我们完全使用toString()。假设我们需要将一个对象转换为字符串。现在尝试使用JSON.stringify():console.log(JSON.stringify(user))
我们做到了,卡尔!但是,JSON.stringify()的可能性不限于此。1.使用数组作为第二个参数
您没听错,stringify函数可能有第二个参数。此参数是我们要在控制台中显示的对象的键的数组。假设我们有这样一个对象数组:let users = [
{
id: 1,
login: 'harry',
password: 'qwerty',
status: 'admin',
access: true
},
{
id: 2,
login: 'alice',
password: 'qwerty',
status: 'user'
},
{
id: 3,
login: 'bob',
password: 'qwerty',
status: 'user'
},
{
id: 4,
login: 'john',
password: 'qwerty',
status: 'user'
},
{
id: 5,
login: 'jane',
password: 'qwerty',
status: 'user'
}
]
...,我们想查看哪个用户是管理员(管理员具有“访问”属性)。如果使用console.log(JSON.stringify(用户)),则会得到以下信息:[{"id":1,"login":"harry","password":"qwerty","status":"admin", "access": true},{"id":2,"login":"alice","password":"qwerty","status":"user"},{"id":3,"login":"bob","password":"qwerty","status":"user"},{"id":4,"login":"john","password":"qwerty","status":"user"},{"id":5,"login":"jane","password":"qwerty","status":"user"}]
同意,不是很可读。现在尝试以下操作:console.log(JSON.stringify(users, ['id', 'access']))
好多了。公平地讲,应该注意的是,在这种情况下,我们可以使用console.table(users):
...但是我们在谈论JSON.stringify(),因此我们不会分心。这个例子不是很好,但是我认为想法很明确。2.使用函数作为第二个参数
该函数将每个键值对评估为第二个参数,以根据该函数的逻辑进行字符串化。如果返回undefined,则不会显示相应的键值对。例:const result = JSON.stringify(users, (key, value) => {
if (typeof value === 'string') return undefined
return value
})
console.log(result)
3.使用数字作为第三个参数
第三个参数负责空格。如果此参数为数字,则每个行级别将具有一个相应的缩进:console.log(JSON.stringify(user, null, 2))
我们得到以下内容:{
"name": "Harry Heman",
"age": 29,
"job": "developer"
}
4.使用字符串作为第三个参数
如果第三个参数是字符串,那么将使用此字符串的字符代替空格:console.log(JSON.stringify(user, null, '->'))
我们得到以下内容:{
->"name": "Harry Heman",
->"age": 29,
->"job": "developer"
}
5. toJSON方法
toJSON方法可以是任何对象的属性。JSON.stringify()返回此函数的结果,而不转换整个对象:const user = {
first: 'Harry',
last: 'Heman',
age: 29,
toJSON(){
return {
full: `${this.first} ${this.last}`
}
}
}
console.log(JSON.stringify(user))
奖金
除了JSON.stringify()和toJSON()之外,还有一个json()方法可返回promise(承诺)。服务器请求中使用此方法。用法示例:const url = 'https://jsonplaceholder.typicode.com/users'
asyncAwaitFetch()
async function asyncAwaitFetch(){
try {
const response = await fetch(url)
const data = await response.json()
console.table(data)
} catch (error){
console.error(error)
} finally {
console.log('')
}
}
我们得到以下信息:
谢谢您的关注。编码愉快!