Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-11-23 15:28:17
Original
491 people have browsed it

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

JSON.stringify for ES6 Maps

When migrating from JavaScript objects to ES6 Maps, JSON.stringify support becomes essential. This article addresses the challenge of serializing Maps for JSON transmission.

Utilizing JSON.stringify Replacer

JSON.stringify offers a second argument, replacer, which can enhance its functionality. Define a replacer function that handles Map objects:

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

Deserialization with JSON.parse Reviver

Likewise, JSON.parse also has a reviver argument to customize object creation during deserialization:

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

To serialize and deserialize an ES6 Map using these functions:

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 replacer and reviver can handle deeply nested data structures containing arrays, objects, and maps:

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 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template