Make your objects tongue-in-cheek: JSON.stringify(), I put objects into the JSON magic hat!

Jiangcheng Cheerful Pea: Personal homepage

Personal column :《VUE》《javaScript》

Personal website : “Jiangcheng Cheerful Pea”

The ideal of life is for an ideal life!

Table of Contents

introduction

1. JSON.stringify() attribute

replacer

space

toJSON

2. Application scenarios

data transmission

data storage

#logging

Data Display

3. Complete and elegant implementation

4. Precautions

circular reference

special type

Performance optimization


Introduction

In JavaScript, JSON.stringify() is a built-in function that converts JavaScript objects to JSON strings. JSON (JavaScript Object Notation) is a lightweight data exchange format that is widely used for front-end and back-end data transmission and storage. This article will introduce the properties and application scenarios of JSON.stringify() in detail, and provide a complete and elegant implementation that handles circular references, special types (such as dates and regular expressions), and performance-related issues. We will also discuss caveats and relevant citations.

1. JSON.stringify() property

The JSON.stringify() function has the following properties:

replacer

replacer is an optional parameter, which can be a function or an array. It is used to specify the properties of the object that need to be serialized. When replacer is a function, it will be applied to each property of the object and can be used to filter, replace, or transform the property’s value. When replacer is an array, only the properties contained in the array will be serialized.

Example:

const obj = {
  name: 'John',
  age: 25,
  address: {
    city: 'New York',
    country: 'USA'
  }
};

const jsonString = JSON.stringify(obj, ['name', 'age']);
console.log(jsonString);
// Output: {"name":"John","age":25}

space

space is an optional parameter that controls the indentation and formatting of the generated JSON string. It can be a number representing the number of spaces to indent, or a string representing the string to indent. If space is a nonnegative integer, the specified number of spaces is used for each level of indentation; if space is a string, that string is used as the indentation symbol.

Example:

const obj = { name: 'John', age: 25 };

const jsonString = JSON.stringify(obj, null, 2);
console.log(jsonString);
//output:
// {
// "name": "John",
// "age": 25
// }

toJSON

If the object being serialized has a toJSON() method, that method will be called to return a serializable value. The toJSON() method can be defined in an object to customize the behavior of the object during serialization.

Example:

const obj = {
  name: 'John',
  age: 25,
  toJSON: function() {
    return {
      fullName: this.name,
      yearsOld: this.age
    };
  }
};

const jsonString = JSON.stringify(obj);
console.log(jsonString);
// Output: {"fullName":"John","yearsOld":25}

2. Application Scenario

JSON.stringify() is useful in the following scenarios:

data transfer

When you need to convert a JavaScript object into a string for transmission over the network to a backend or other system, you can use JSON.stringify() for serialization.

const obj = { name: 'John', age: 25 };

const jsonString = JSON.stringify(obj);
console.log(jsonString);
// Output: {"name":"John","age":25}

data storage

If you need to save a JavaScript object to local storage (such as the browser’s LocalStorage or a database), you can use JSON.stringify() to convert the object to a JSON string before storing it.

const obj = { name: 'John', age: 25 };

const jsonString = JSON.stringify(obj);
localStorage.setItem('user', jsonString);

Logging

When logging, JavaScript objects can be converted to JSON strings and used as part of the log message.

const obj = { name: 'John', age: 25 };

const logMessage = `User info: ${JSON.stringify(obj)}`;
console.log(logMessage);

Data display

After converting the JavaScript object into a JSON string, it can be easily displayed, rendered or printed in the front-end page.

const obj = { name: 'John', age: 25 };

const jsonString = JSON.stringify(obj);
document.getElementById('user-info').textContent = jsonString;

3. Complete and elegant implementation

Below is a complete and elegant implementation of JSON.stringify() that takes into account special types such as circular references, dates, and regular expressions, while maintaining performance optimizations as much as possible.

function stringify(obj) {
  const seen = new WeakSet(); // Used to detect circular references
  const typeMap = {
    '[object Date]': 'Date',
    '[object RegExp]': 'RegExp',
  };

  function isObject(value) {
    return typeof value === 'object' & amp; & amp; value !== null;
  }

  function handleSpecialTypes(value) {
    if (value instanceof Date) {
      return { type: 'Date', value: value.toISOString() };
    } else if (value instanceof RegExp) {
      return { type: 'RegExp', value: value.toString() };
    }
    return value;
  }

  function replacer(key, value) {
    if (seen.has(value)) {
      throw new TypeError('Converting circular structure to JSON');
    }

    if (isObject(value)) {
      seen.add(value);
    }

    value = handleSpecialTypes(value);

    return value;
  }

  function stringifyHelper(obj) {
    if (isObject(obj)) {
      if (Array.isArray(obj)) {
        return '[' + obj.map((item) => stringifyHelper(item)).join(',') + ']';
      } else {
        const properties = Object.keys(obj)
          .map((key) => `"${key}":${stringifyHelper(obj[key])}`)
          .join(',');
        return `{${properties}}`;
      }
    } else {
      return JSON.stringify(obj, replacer);
    }
  }

  return stringifyHelper(obj);
}

This implementation uses recursion and some helper functions to handle different data types. It checks for circular references and throws errors, handles special types like dates and regular expressions, and uses recursion for depth-first traversal.

Please note that this implementation is only a simplified example and more processing and optimization may be required for more complex scenarios. It is recommended to refer to third-party libraries or more comprehensive documentation and resources for actual use.

4. Notes

In use

When using JSON.stringify(), you need to pay attention to the following:

Circular Reference

If the objects to be serialized have circular references, that is, objects refer to each other, it will lead to infinite recursion. In order to avoid infinite loops, you can use WeakSet or other methods to detect circular references, and throw an error or take other handling methods when a circular reference is detected.

Special type

Special types such as dates and regular expressions require appropriate handling to ensure correct serialization and deserialization.

Performance Optimization

JSON.stringify() may cause performance issues when dealing with large objects or deeply nested objects. To improve performance, consider using more efficient algorithms or employing other optimization strategies.