Home  >  Article  >  Web Front-end  >  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
Mary-Kate OlsenOriginal
2024-11-20 13:00:22222browse

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;
  }
}
function reviver(key, value) {
  if (typeof value === 'object' && value !== null) {
    if (value.dataType === 'Map') {
      return new Map(value.value);
    }
  }
  return value;
}

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);

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);

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!

Statement:
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