Select Page

How to Solve Python TypeError: Object of type map is not JSON serializable

by | Programming, Python, Tips

This error occurs when you try to serialize a map object to a JSON string using the json.dumps() method. You can solve this error by converting the map to a list using the list() method. For example,

import json

lst = [2, 7, 19, 20]

res = map(lambda x: x ** 2, lst)

json_str = json.dumps(list(res))

This tutorial will go through how to solve the error with code examples.


TypeError: Object of type map is not JSON serializable

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type. The part “Object of type map” tells us the error is due to an illegal operation with a map object.

Serialization in Python refers to converting a Python object into a transmittable format that we can recreate when needed using deserialization. JSON serialization returns a human-readable string form called a JSON string. The JSON encoder json.dump() and json.dumps() can only serialize certain object types like dictionaries, lists, or strings.

is not JSON serializable” informs us that the JSON serialization is an illegal operation for the map type.

Example

Let’s look at an example of serializing a map object. First, we will import the json module and then define a list of integers.

import json

lst = [2, 4, 9, 12, 7]

Next, we will use the map function to execute an anonymous function for each item in the list.

res = map(lambda x: x ** 2, lst)

In the above code, the map function executes an anonymous or lambda function which squares each item in the list.

Next, we will try to serialize the result of the map function call by passing it to the json.dumps() method.

json_str = json.dumps(res)
print(json_str)

Let’s run the code to see the result:

TypeError: Object of type map is not JSON serializable

The error occurs because the map() function call returns a map object, which is not JSON serializable. We can check the type of an object using the type() method as follows:

print(type(res))
<class 'map'>

Solution #1: Convert the map object to a list

The simplest way to solve this error is to convert the map object to a list using the built-in list() method. The list data type is JSON serializable.

Let’s look at the revised code:

import json

lst = [2, 4, 9, 12, 7]

res = map(lambda x: x ** 2, lst)

json_str = json.dumps(list(res))
print(json_str)

Let’s run the code to see the JSON string:

[4, 16, 81, 144, 49]

Solution #2: Define a custom function for the default kwarg

We can also solve this error by defining a custom function that converts a map object to a list. We can then pass the function as the default argument for the json.dumps() method. The function we set default to gets called for objects that are not JSON serializable. Let’s look at the custom function:

import json

def serialize_map(obj):

    if isinstance(obj, map):

        return list(obj)

    raise TypeError ("Type %s is not serializable" % type(obj))

Note that if the object obj is not an instance of map the function will raise a TypeError. Let’s set the default keyword argument to our custom function and run the code:

lst = [2, 4, 9, 12, 7]

res = map(lambda x: x ** 2, lst)

json_str = json.dumps(res, default=serialize_map)

print(json_str)
[4, 16, 81, 144, 49]

Solution #3: Define a JSONEncoder subclass for the cls kwarg

We can also solve this error by building a custom JSONEncoder subclass. This subclass will override the default method to serialize additional types.

import json

class map_encoder(json.JSONEncoder):

    def default(self, obj):

        if isinstance(obj, map):

            return list(obj)

        return json.JSONEncoder.default(self, obj)

Similar to the custom function, the default method of the map_encoder class checks if the object is of type map, converts it to a list and returns it.

We have to specify the custom JSONEncoder subclass with the cls keyword argument. Otherwise, JSONEncoder is used. Let’s look at the updated code:

lst = [2, 4, 9, 12, 7]

res = map(lambda x: x ** 2, lst)

json_str = json.dumps(res, cls=map_encoder)
print(json_str)

Let’s run the code to see the result:

[4, 16, 81, 144, 49]

Below is the collection of objects that the JSONEncoder class supports by default, and their JSON equivalent.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int- & float- derived Enumsnumber
Truetrue
Falsefalse
Nonenull
JSONEncoder Supported objects and types by default

Summary

Congratulations on reading to the end of this tutorial.

For further reading on errors involving JSON serialization, go to the articles:

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!