Home > Web Front-end > JS Tutorial > How to Serialize and Deserialize ES6 Maps with JSON.stringify and JSON.parse?

How to Serialize and Deserialize ES6 Maps with JSON.stringify and JSON.parse?

Mary-Kate Olsen
Release: 2024-11-20 13:00:22
Original
287 people have browsed it

How to Serialize and Deserialize ES6 Maps with JSON.stringify and JSON.parse?

How to Serialize ES6 Maps for JSON Processing

When making the switch from ES6 Objects to Maps, the inability to directly JSON.stringify a Map can be a hindrance. This article delves into a solution to this challenge, using the second argument of both JSON.stringify and JSON.parse, replacer and reviver, respectively.

Custom Replacer and Reviver Functions

To add support for Maps, custom replacer and reviver functions can be created. These functions handle the conversion to and from JSON:

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
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 the custom functions in place, serializing and deserializing Maps becomes straightforward:

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 technique extends to deeply nested structures composed of Maps, Arrays, and Objects:

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 to Serialize and Deserialize ES6 Maps with 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