This is the 23rd day of my participation in the August More Text Challenge

Json.stringify () is the canonical method for converting JavaScript objects to JSON. There are many JavaScript frameworks that use json.stringify () internally, such as the Res.json () and Axios Body serialization of the Express framework.

By default, however, json.stringify () outputs in JSON format, without Spaces or colors. Later, we’ll use a common NPM package to color the output data.

The basic usage of json.stringify () is as follows:

const think = { eat: '🥩'.sleep: '😴' }
​
console.log(JSON.stringify(think)) / / {" eat ", "🥩", "sleep" : "😴}"console.log(JSON.stringify(think, null.2))
/* {"eat": "🥩", "sleep": "😴"} */
Copy the code

As you can see, our output using json.stringify () is much more readable.

TAB spacing

You can also pass in a “\t” TAB spacing to format the output data.

const think = { eat: '🥩'.sleep: '😴' }
​
console.log(JSON.stringify(think, null.'\t'))
​
/* {"eat": "🥩", "sleep": "😴"} */
Copy the code

Space parameters

The third argument to json.stringify controls the spacing. It is this that provides beautiful string output.

It allows two types of arguments: Number and String.

Number

If Space is a Number type, this represents the corresponding Number of Spaces that json.stringify will place before each key. You can use any number between 0 and 10 as an indent.

const think = { eat: '🥩'.sleep: '😴' }
​
console.log(JSON.stringify(think, null.2))
/* {"eat": "🥩", "sleep": "😴"} */
Copy the code

String

Alternatively, you can use a string as an indent. A maximum of 10 characters are allowed. If you try to pass more than 10 characters, it will only use the first 10 characters.

const think = { eat: '🥩'.sleep: '😴' }
​
console.log(JSON.stringify(think, null.' I Love '))
/ * {I Love "eat" : "🥩," I Love "sleep" : "😴} * /
Copy the code

Express and Axios

For frameworks that do not call json.stringify () directly, there is usually an option to set the Spaces argument. For example, Express has a global ‘JSON Spaces’ option that allows you to set Spaces for all res.json() calls.

const express = require('express')
const app = express()
​
/ / set the Spaces
app.set('json spaces'.2)
app.get(The '*'.(req, res) = > res.json({ name: 'O.O'.age: 20 }))
​
const axios = require('axios')
​
const res = await axios.get('http://localhost:3000', {
  transformResponse: body= > body // Disable JSON parsing so res.data is a string
})
​
console.log(res.data)
/* { "name": "O.O", "age": 20 } */
Copy the code

Axios does not have an explicit option to set the JSON format, but you can handle the JSON serialization yourself using the transformRequest option. The key syntax is:

const axios = require('axios')
​
const obj = {
  name: 'O.O'.age: 20.address: 'xxx'
}
​
const res = await axios.post('http://localhost:5000', obj, {
  transformRequest: data= > JSON.stringify(data, null.2), // Send a nice JSON format
  transformResponse: body= > body
})
​
console.log(res.data)
/* { "name": "O.O", "age": 20 } */
Copy the code

Prettyjson

Prettyjson Formats JSON data in YAML style. Prettyjson only works on the CLI, and you can’t get colors if you send Prettyjson output as an HTTP response.

Here is an example of printing JSON from Node.js using Prettyjson:

const prettyjson = require('prettyjson')
​
console.log(prettyjson.render({
  name: 'IU'.age: 18.love: 'me'.hobby: 'sing'
}))
Copy the code

The effect is as follows:

You should use methods like the above to highlight the data you want to improve readability.

Replacer parameter

In addition, the second argument to json.stringify, replacer, can be used to convert the result.

It allows two types of arguments: Array and Function.

Array

const user = {
  name: 'IU'.age: 18.love: 'me'.hobby: 'sing'
}
​
console.log(JSON.stringify(user, ['name'.'love'].2))
/* { "name": "IU", "love": "me" } */
Copy the code

Function

We call function once for each item, or you can loop over each item and operate on each pass using the logic defined in the function.

Here is an example where I skip properties whose values are not strings. In other words, I only want to display items with numeric values.

const user = {
  name: 'IU'.age: 18.love: 'me'.hobby: 'sing'
}
​
const replacer = function (key, value) {
  if (typeofvalue ! = ='string') return value
  return undefined
}
​
console.log(JSON.stringify(user, replacer, 2))
/* { "age": 18 } */
Copy the code