Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Python
  3. Question
Python

Python - TypeError: Object of type 'int64' is not JSON serializable

Asked by Chris Evans Apr 13, 2021 13.1K views 3 answers
Share

About this question

I have a Dataframe that stores Store name and daily sales count. I am trying to insert this to Salesforce using the below Python script. I, however, get an error.

TypeError: Object of type 'int64' is not JSON serializable

Given below is the view of the dataframe:

Storename,Count

Store A,10

Store B, 12

Store C, 5

I use the below code to insert it to Salesforce:

update_list = []
for i in range((len(store))):
    update_data = {
               'name' :    store['entity_name'].iloc[i],
                'count__c': store['count'].iloc[i] }
    update_list.append(update_data)
sf_data_cursor = sf_datapull.salesforce_login()
sf_data_cursor.bulk.Account.update(update_list)

Get the error the last line above gets executed. Could anyone assist in fixing this. Thanks.


Your answer

3 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Feb 21, 2025

The error "TypeError: Object of type 'int64' is not JSON serializable" in Python occurs when trying to convert a NumPy int64 object into JSON using json.dumps(). The built-in JSON encoder in Python does not recognize NumPy data types directly.


Why Does This Happen?

json.dumps() only supports basic Python data types like int, str, float, dict, etc.

NumPy data types (int64, float32, etc.) are not natively serializable in JSON.

How to Fix It?

1. Convert NumPy int64 to Python int

Before serializing, convert int64 to a regular Python int:

import numpy as np
import json
data = {"value": np.int64(100)}  
json_str = json.dumps(data, default=int)  # Convert int64 to int  
print(json_str)  # Output: {"value": 100}

2. Use a Custom JSON Encoder

If there are multiple NumPy types, use a custom encoder:

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):  # Convert all NumPy integers
            return int(obj)
        if isinstance(obj, np.floating):  # Convert all NumPy floats
            return float(obj)
        return super().default(obj)
data = {"value": np.int64(42)}
json_str = json.dumps(data, cls=NumpyEncoder)
print(json_str)

3. Manually Convert the Whole Data Structure

If working with lists or dictionaries, convert all NumPy types before serialization:

data = {"values": list(map(int, np.array([1, 2, 3], dtype=np.int64)))}
json_str = json.dumps(data)

Was this helpful?

Ranjana Admin JanBask Expert

Answered on Apr 26, 2024

The error message "TypeError: Object of type 'int64' is not JSON serializable" typically occurs when trying to serialize an integer using the json.dumps() function in Python, and the integer is of type int64 from the NumPy library.


To resolve this issue, you can convert the int64 object to a standard Python integer before serializing it to JSON. You can do this using the int() function to explicitly cast the value to an integer. Here's an example:

import json
import numpy as np
# Example of an int64 object
int64_value = np.int64(42)
# Convert int64 to Python integer
standard_int = int(int64_value)
# Serialize the integer to JSON
json_data = json.dumps(standard_int)
print(json_data)

In this example, int64_value is the NumPy int64 object that we want to serialize. By converting it to a standard Python integer using int(int64_value), we ensure that it can be serialized to JSON without raising the TypeError. Finally, we use json.dumps() to serialize the integer to a JSON-formatted string.

Make sure to replace int64_value with the actual variable or value that you are trying to serialize.


Was this helpful?

More Python discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Python Blogs

Guides, tips and career advice on Python from JanBask experts.