A prelude to

Json.stringify () is commonly used when sending data from the front end to the back end.

JSON.stringify()

Use to convert JavaScript values to JSON strings

grammar

JSON.stringify(value[, replacer[, space]])
Copy the code

parameter

  • Value: must, usually a JavaScript value (usually an object or array)

  • Replacer: optional.

    • If the argument is a function, each attribute of each serialized value is processed by the function
    • If the parameter is an array, only properties whose property names are in the array will be serialized
  • Space: the optional.

    • Specifies an indent blank string to beautify the output
    • If the parameter is a number, it indicates how many Spaces there are. The upper limit is 10. If the parameter is less than 1, there is no space
    • Space can also use non-numerals, as in: \t
    • If it is a string, the string is used as a space.

The return value

A JSON string representing the given value.

The basic use

  • Json.stringify () can convert objects or values. (Generally, objects are converted.)

    // 1
    JSON.stringify({
        name: "xiaoqi".age: 20
      })
    // '{"name":"xiaoqi","age":20}'// 2
    console.log(JSON.stringify(1)); //  "1"
    console.log(JSON.stringify("xiaoqi")); // "xiaoqi"
    console.log(JSON.stringify(true)); // "true"
    console.log(JSON.stringify(null)); // "null"
    Copy the code
  • Replacer is specified as a function, optionally converted

      JSON.stringify(
        {
          name: "xiaoqi".age: 20
        },
        (key, value) = > {
          console.log(key, value, "- > > > > >");
          returnvalue; })Copy the code

    You can see that the first line outputs the original object. When replacer is a function, the first argument is not the key-value pair of the object, key is an empty string, and value is the original object.

    Using this feature of the function can break some of the features of json.stringify () itself.

    const obj = {
      name: "xiaoqi".age: undefined.special: Symbol("dcd"),
      hobby: () = > "programming"
    };
    ​
    console.log(JSON.stringify(obj)); // '{"name":"xiaoqi"}'console.log(
      JSON.stringify(obj, (key, value) = > {
        const type = typeof value;
        switch (true) {
          case type === "undefined":
            return "undefined";
          case type === "symbol":
            return value.toString();
          case type === "function":
            return value.toString();
          default:
            break;
        }
        returnvalue; }));// '{"name":"xiaoqi","age":"undefined","special":"Symbol(dcd)","hobby":"function hobby() { return "programming"; }} '" "
    Copy the code

    Replacer can also be set as a function when the back end needs the front end to be null, and does not pass “, null, or undefined.

    const obj = {
      name: "xiaoqi".age: undefined.height: null.text: ""
    };
    console.log(JSON.stringify(obj, (key, value) = >(! value ?undefined : value)));
    // '{"name":"xiaoqi"}'
    Copy the code
  • When replacer is specified as an array, it acts as a filter that converts the specified properties.

    console.log(
      JSON.stringify(
        {
          name: "xiaoqi".age: 20},"name"]));// '{"name":"xiaoqi"}'
    Copy the code
  • Use the third argument, space, to beautify the output

     JSON.stringify({
          name: "xiaoqi".age: 20
        }, null.'\t')
    /* '{ "name": "xiaoqi", "age": 20 }' */
    Copy the code

features

  • undefined, functions,symbolValues are ignored in non-array objects.

    const obj = {
      name: "xiaoqi".age: undefined.special: Symbol("dcd"),
      hobby: () = > "programming"
    };
    console.log(JSON.stringify(obj)); // '{"name":"xiaoqi"}'
    Copy the code
  • undefined, functions,symbolThe value in the array will be converted tonull.

    const obj = ["xiaoqi".undefined.Symbol("dcd"), () = > "programming"];
    console.log(JSON.stringify(obj)); // ["xiaoqi",null,null,null] 
    Copy the code
  • undefined, functions,symbolThe value is converted to in a separate conversionundefined.

    console.log(JSON.stringify(undefined)); // undefined
    console.log(JSON.stringify(Symbol("dcd"))); // undefined
    console.log(JSON.stringify(() = > "programming")); // undefined
    Copy the code
  • Bools, strings, and numeric wrapper objects are converted to their original values.

    // Wrap the object
    console.log(JSON.stringify([new Number(1), new Boolean(false), new String("112")));// [1,false,"112"] 
    Copy the code
  • All tosymbolValues as key attributes are ignored, even inreplacerA function forced return does not work either.

    console.log(JSON.stringify({[Symbol("dcd")]: "xiaoxi" })); / / '{}'
    console.log(
      JSON.stringify({ [Symbol("dcd")]: "xiaoxi" }, (key, value) = > {
        if (typeof key === "symbol") {
          returnvalue; }}));// undefined
    Copy the code
  • DateThe object is converted to a string

    console.log(JSON.stringify(new Date())); / / "the 2021-12-07 T02:40:07. 609 z"
    Copy the code
  • The RegExp object will be converted to {}

    console.log(JSON.stringify(new RegExp())); / / '{}'
    Copy the code
  • NaN, Infinity, and NULL are all converted to NULL as attribute values.

    console.log(JSON.stringify({ name: null.age: NaN.height: Infinity })); 
    // {"name":null,"age":null,"height":null}
    Copy the code
  • Converted value If a toJSON method exists, the value returned by the toJSON method becomes the final converted value

    console.log(
      JSON.stringify({
        name: "xiaoqi".toJSON() {
          return "lalalla"; }}));Copy the code
  • For objects, only enumerable attributes are serialized

    const object1 = {};
    ​
    Object.defineProperty(object1, "age", {
      value: 42.enumerable: false
    });
    ​
    console.log(JSON.stringify(object1)); / / '{}'
    Copy the code
  • The object referenced by the loop

    const obj1 = [{](url)
      name: "xiaoqi"
    };
    ​
    obj1.child = obj1;
    ​
    console.log(JSON.stringify(obj1)); // TypeError: Converting circular structure to JSON
    Copy the code
  • An error is reported when converting a value of type BigInt

    console.log(JSON.stringify(BigInt(99999999999999))); // TypeError: Do not know how to serialize a BigInt
    Copy the code

Exception handling

Json.stringify is error-prone, and we generally wrap a secure jsonStringify in our work.

/** * the object is converted to a JSON format string */
export const jsonStringify = (value: any) = > {
  try {
    return JSON.stringify(value)
  } catch (err) {
    // Reports logs
    sendLog('error'.`[jsonStringify] error: ${err.message}`.'js_error')
    return "" '"}}Copy the code

The end of the

Refer to the article

  • MDN — JSON.stringify()
  • I almost lost my annual bonus because of json.stringify