How to Convert a Map to JSON in JavaScript | bobbyhadz

How to Convert a Map to JSON in JavaScript

Convert a Map to JSON in JavaScript #

To convert a Map to JSON:

  1. Use the Object.fromEntries() method to convert the Map to an object.
  2. Pass the object to the JSON.stringify() method.
  3. The JSON.stringify() method converts the passed in value to a JSON string.

index.js

const

map

=

new

Map

(

[

[

'name'

,

'Tom'

]

,

[

'country'

,

'Chile'

]

,

]

)

;

const

json

=

JSON

.

stringify

(

Object

.

fromEntries

(

map

)

)

;

console

.

log

(

json

)

;

We used the
Object.fromEntries
method to convert a Map to an object.

index.js

const

map

=

new

Map

(

[

[

'name'

,

'Tom'

]

,

[

'country'

,

'Chile'

]

,

]

)

;

const

obj

=

Object

.

fromEntries

(

map

)

;

console

.

log

(

obj

)

We had to do this because Map objects don’t have native support for serialization or parsing.

The next step is to pass the object to the
JSON.stringify
method.

The JSON.stringify method converts the object to a JSON string and returns the
result.

If you need to convert the JSON string back to a Map, you have to:

  1. Use the JSON.parse method to parse the JSON string into an object.
  2. Use the Object.entries method to get an array of key-value pairs.
  3. Call the Map() constructor with the array of key-value pairs.

index.js

const

map

=

new

Map

(

[

[

'name'

,

'Tom'

]

,

[

'country'

,

'Chile'

]

,

]

)

;

const

json

=

JSON

.

stringify

(

Object

.

fromEntries

(

map

)

)

;

const

obj

=

JSON

.

parse

(

json

)

;

const

mapAgain

=

new

Map

(

Object

.

entries

(

obj

)

)

;

console

.

log

(

mapAgain

)

;

The Object.entries method takes an object and returns a two-dimensional array.

index.js

console

.

log

(

Object

.

entries

(

{

name

:

'Tom'

,

country

:

'Chile'

}

)

)

;

The
Map()
constructor expects an iterable whose elements are key-value pairs, so we can
directly pass it the result from calling the Object.entries method.

To get around the fact that Map objects don’t have native support for serialization or parsing, we convert the Map to an object and serialize the object.

Further Reading #