You may not know JSON.stringfy usage

EDITORIAL

JSON.stringfy()It is a JavaScript object into JSON format string in a standard way . Many JavaScript frameworks in its interior, will be used JSON.stringify(): Express 's res.json(), Axios 's post, and WebPACK stats , they are called JSON.stringify(), and contains an error cases.

Getting started is simple

All modern JavaScript support run-time JSON.stringify(), even IE8 supports it. The following is a simple object into the JSONexample:

const obj = { answer: 42 };

const str = JSON.stringify(obj);
str; // '{"answer":42}'
typeof str; // 'string'

You may often see JSON.stringify()and JSON.parse()together with the use of scenes, like the following code, as this model is to achieve a deep copy of one of the ways:

const obj = { answer: 42 };
const clone = JSON.parse(JSON.stringify(obj));

clone.answer; // 42
clone === obj; // false

Errors and edge cases

JSON.stringify()In the presence of circular references transformation object will throw an error . More simply put, it is that if an object has a property that points to itself, JSON.stringify()will throw an error, such as:

const obj = {};
// 存在循环引用的对象,它指向它本身
obj.prop = obj;

// 会抛出 "TypeError: TypeError: Converting circular structure to JSON" 异常
JSON.stringify(obj);

This is JSON.stringify()will throw an exception only case, unless you custom by declaring toJSON()methods or replacerfunctions. Nevertheless, you should still be JSON.stringify()included in the try/catchstatement because circular references are very common in practice.

Meanwhile, some of the boundaries with the following example, JSON.stringify()and does not throw an error, but you might expect, but it throws an error. For example, JSON.stringify()it will NaNand Infinityconverted to null:

const obj = { nan: parseInt('not a number'), inf: Number.POSITIVE_INFINITY };

JSON.stringify(obj); // '{"nan":null,"inf":null}'

JSON.stringify()Those values are also directly be omitted functionsand undefinedthe properties as follows:

const obj = { fn: function() {}, undef: undefined };

// 它会返回空对象
JSON.stringify(obj); // '{}'

format

JSON.stringify()The first parameter is the sequence into JSONan object. JSON.stringify()Actually it takes three parameters, and the third argument is called spaces. spacesParameter is used by adopting an approach to improve the readability of the format JSONstring.

You can pass the type stringor numberthe spacesparameters. If spacesis undefined, it JSON.stringify()will be placed on a separate line for each key, while the right to increase its indented spaces, such as:

const obj = { a: 1, b: 2, c: 3, d: { e: 4 } };

// '{"a":1,"b":2,"c":3,"d":{"e":4}}'
JSON.stringify(obj);

// {
//   "a": 1,
//   "b": 2,
//   "c": 3,
//   "d": {
//     "e": 4
//   }
// }
JSON.stringify(obj, null, '  ');

// 数字 2 会达到和上面一样的效果,它代表空格的个数
JSON.stringify(obj, null, 2);

spaces Strings do not have a space, although we would usually use spaces, such as it can be underlined:

// {
// __"a": 1,
// __"b": 2,
// __"c": 3,
// __"d": {
// ____"e": 4
// __}
// }
JSON.stringify(obj, null, '__');

Replacers

JSON.stringify()The second parameter is replacera function. In the foregoing example, it is equal null. JavaScript objects have a key-value pair for each call to replacerthe function, and its return value will be used as a value after formatting, such as:

const obj = { a: 1, b: 2, c: 3, d: { e: 4 } };

// 使每个属性的值递增 1
// '{"a":2,"b":3,"c":4,"d":{"e":5}}'
JSON.stringify(obj, function replacer(key, value) {
  if (typeof value === 'number') {
    return value + 1;
  }
  return value;
});

replacerFunction when sensitive data is omitted, very useful. Suppose you want to omit all contain passwordattributes:

const obj = {
  name: 'Jean-Luc Picard',
  password: 'stargazer',
  nested: {
    hashedPassword: 'c3RhcmdhemVy'
  }
};

// '{"name":"Jean-Luc Picard","nested":{}}'
JSON.stringify(obj, function replacer(key, value) {
  // 这个函数会被调用 5 次,这里的 key 依次为:
  // '', 'name', 'password', 'nested', 'hashedPassword'
  if (key.match(/password/i)) {
    return undefined;
  }
  return value;
});

toJSON method

JSON.stringify()The method of traversing the object at the same time, will focus on those with toJSON()property methods. If it finds toJSON()method, JSON.stringify()calls it, then it will replace the value of the return value after formatting, such as:

const obj = {
  name: 'Jean-Luc Picard',
  nested: {
    test: 'not in output',
    toJSON: () => 'test'
  }
};

// '{"name":"Jean-Luc Picard","nested":"test"}'
JSON.stringify(obj);

toJSON()The method can return any value, including the object, the type of base, or undefined. If you toJSON()return undefined, JSON.stringify()you will ignore this property.

Many JavaScript modules toJSON()to ensure the correctness of the sequence of complex objects, such as Mongoose documentsand Momentobjects .

At last

JSON.stringify()JavaScript is the core of the more basic approach. Many libraries and frameworks use it in its interior, therefore, in-depth understanding of it, can help you make better use of your favorite npmmodules. For example, you can use the Express REST API in toJSONa method for formatting a native Datetype, or Axios, it is possible to correctly transmit the object contains a circular reference requests over HTTP.

Original link: http://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html

Reproduced in: https: //www.jianshu.com/p/8c29f32dee07

Guess you like

Origin blog.csdn.net/weixin_33724046/article/details/91259271