Home > Web Front-end > JS Tutorial > How Can I Serialize and Deserialize ES6 Maps Using JSON.stringify() and JSON.parse()?

How Can I Serialize and Deserialize ES6 Maps Using JSON.stringify() and JSON.parse()?

Barbara Streisand
Release: 2024-11-21 03:13:14
Original
175 people have browsed it

How Can I Serialize and Deserialize ES6 Maps Using JSON.stringify() and JSON.parse()?

JSON.stringify() and ES6 Maps

ES6 Maps provide a powerful alternative to JavaScript objects, but serializing them using JSON.stringify() can be challenging. To overcome this obstacle, you can leverage the replacer function in JSON.stringify() and its counterpart reviver in JSON.parse().

Custom Serialization with replacer

The replacer function allows you to customize how objects are serialized. In this case, you can modify it to handle Map objects:

function replacer(key, value) {
  if(value instanceof Map) {
    return {
      dataType: 'Map',
      value: Array.from(value.entries()), // or with spread: value: [...value]
    };
  } else {
    return value;
  }
}
Copy after login

Custom Deserialization with reviver

Similarly, the reviver function lets you alter how objects are deserialized. You can use it to restore Map objects:

function reviver(key, value) {
  if(typeof value === 'object' && value !== null) {
    if (value.dataType === 'Map') {
      return new Map(value.value);
    }
  }
  return value;
}
Copy after login

Usage

With these functions defined, you can now effectively JSON.stringify() and JSON.parse() Map objects:

const originalValue = new Map([['a', 1]]);
const str = JSON.stringify(originalValue, replacer);
const newValue = JSON.parse(str, reviver);
console.log(originalValue, newValue);
Copy after login

Deep Nesting

The provided solutions support deep nesting of arrays, objects, and Maps, as demonstrated below:

const originalValue = [
  new Map([['a', {
    b: {
      c: new Map([['d', 'text']])
    }
  }]])
];
const str = JSON.stringify(originalValue, replacer);
const newValue = JSON.parse(str, reviver);
console.log(originalValue, newValue);
Copy after login

The above is the detailed content of How Can I Serialize and Deserialize ES6 Maps Using JSON.stringify() and JSON.parse()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template