Must know the front end will be --JSON.stringify () sharp third parameter

  • Author: Xiaohua firmly on King
  • Suggested Reading time: 2 min
  • Original blog

JSON.stringify () is a front-end method frequently used, this function can be passed three parameters, here I Amway Dir three parameters, specifically designed to 美化输出, look under the syntax:

JSON.stringify(value[, replacer [, space]])
复制代码

Below I have listed three common example, directly on the code

Common usage

let obj = {
  a: 'foo',
  b: 'bar',
}

console.log(JSON.stringify(obj))

// "{"a":"foo","b":"bar"}"
复制代码

Incoming digital space

let obj = {
  a: 'foo',
  b: 'bar',
}

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

/*
{
  "a": "foo",
  "b": "bar"
}
*/
复制代码

space incoming string

let obj = {
  a: 'foo',
  b: 'bar',
}

console.log(JSON.stringify(obj, null, '--'))

/*
{
--"a": "foo",
--"b": "bar"
}
*/
复制代码

A typical application scenarios

No console or on the phone, I want to output an object, which will be used when alert:

alert(obj);
复制代码

The effect is like this:

At this point you:

Later, you use a third parameter JSON.stringify of:

alert(JSON.stringify(obj, null, 2));
复制代码

The natural result is very clear:

How, it is not so cool, space incoming numbers should meet most needs, so I would recommend everyone to use.

Reproduced in: https: //juejin.im/post/5d0b45866fb9a07ed136db0f

Guess you like

Origin blog.csdn.net/weixin_33889665/article/details/93164524