TypeError: Object of type DataFrame is not JSON serializable

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: Object of type DataFrame is not JSON serializable #

The Python "TypeError: Object of type DataFrame is not JSON serializable" occurs when we try to serialize a DataFrame object to JSON using the json.dumps method. To solve the error, use the to_json() method instead, e.g. df.to_json().

Here is an example of how the error occurs

main.py
import json import pandas as pd df = pd.DataFrame( { "Name": [ "Alice", "Bob", "Carl", ], "Age": [29, 30, 31], } ) # ⛔️ TypeError: Object of type DataFrame is not JSON serializable print(json.dumps(df))

We tried passing a DataFrame object to the json.dumps() method but the method doesn't handle DataFrame objects by default.

To solve the error, use the to_json() method on the DataFrame object.

main.py
import pandas as pd df = pd.DataFrame( { "Name": [ "Alice", "Bob", "Carl", ], "Age": [29, 30, 31], } ) # 👇️ '{"Name":{"0":"Alice","1":"Bob","2":"Carl"},"Age":{"0":29,"1":30,"2":31}}' print(df.to_json()) # 👇️ <class 'str'> print(type(df.to_json()))

The to_json() method converts the DataFrame object to a JSON string.

Alternatively, you can try to convert the DataFrame to a dict object before serializing to JSON.

main.py
import json import pandas as pd df = pd.DataFrame( { "Name": [ "Alice", "Bob", "Carl", ], "Age": [29, 30, 31], } ) # 👇️ '{"Name": {"0": "Alice", "1": "Bob", "2": "Carl"}, "Age": {"0": 29, "1": 30, "2": 31}}' print(json.dumps(df.to_dict())) # 👇️ <class 'str'> print(type(json.dumps(df.to_dict())))

The to_dict method converts the DataFrame to a dictionary, which we can then serialize to JSON.

The JSONEncoder class supports the following objects and types by default.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

Conclusion #

The Python "TypeError: Object of type DataFrame is not JSON serializable" occurs when we try to serialize a DataFrame object to JSON using the json.dumps method. To solve the error, use the to_json() method instead, e.g. df.to_json().

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.