5 little-known features of JSON.stringify ()



Good day, friends!

In this short article, I want to tell you about some of the rarely used features of JSON.stringify (). They may be useful to you.

JSON.stringify () is often used during debugging to convert an object or regular string to a string in JSON format. But how is this method used, and can we get around toString ()? Let's try to do it.

//   user
const user = {
    name: 'Harry Heman',
    age: 29,
    job: 'developer'
}

//    ,    toString(),     
console.log(user.toString()) // [object Object]

[object Object] is not exactly what we wanted to see, is it?

Don't ask why we use toString () at all. Suppose we need to translate an object into a string.

Now try using JSON.stringify ():

console.log(JSON.stringify(user)) // {"name":"Harry Heman","age":29, "job": "developer"}

We did it, Carl!

However, the possibilities of JSON.stringify () are not limited to this.

1. Using an array as a second argument


You heard right, the stringify function may have a second argument. This argument is the array of keys of the object that we want to display in the console. Let's say we have such an array of objects:

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'
    }
]

... and we want to see which of the users is the admin (the admin has the “access” property).

If we use console.log (JSON.stringify (users)), we get the following:

[{"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"}]

Agree, not very readable.

Now try the following:

console.log(JSON.stringify(users, ['id', 'access'])) // [{"id":1,"access":true},{"id":2},{"id":3},{"id":4},{"id":5}]

So much better.

In fairness, it should be noted that in this case we could use console.table (users):



... but we are talking about JSON.stringify (), so we are not distracted. The example is not very good, but I think the idea is clear.

2. Using a function as a second argument


The function evaluates each key-value pair as the second argument to stringify according to the logic of this function. If we return undefined, then the corresponding key-value pair is not displayed. Example:

const result = JSON.stringify(users, (key, value) => {
    if (typeof value === 'string') return undefined

    return value
})

console.log(result) // [{"id":1,"access":true},{"id":2},{"id":3},{"id":4},{"id":5}]

3. Using a number as the third parameter


The third argument is responsible for spaces. If this argument is a number, then each line level will have a corresponding indent:

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

We get the following:

{
  "name": "Harry Heman",
  "age": 29,
  "job": "developer"
}

4. Using a string as the third argument


If the third parameter is a string, then the characters of this string will be used instead of spaces:

console.log(JSON.stringify(user, null, '->'))

We get the following:

{
->"name": "Harry Heman",
->"age": 29,
->"job": "developer"
}

5. toJSON method


The toJSON method can be a property of any object. JSON.stringify () returns the result of this function without converting the entire object:

const user = {
    first: 'Harry',
    last: 'Heman',
    age: 29,
    toJSON(){
        return {
            full: `${this.first} ${this.last}`
        }
    }
}

console.log(JSON.stringify(user)) // "full": "Harry Heman"

Bonus


Besides JSON.stringify () and toJSON (), there is also a json () method that returns a promise (promise). This method is used in server requests.

Usage example:

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('')
    }
}

We get the following:



Thank you for your attention.

Happy coding!

All Articles