Typeerror: object of type int64 is not json serializable

Having difficulty troubleshooting the “Typeerror: object of type int64 is not json serializable” error?

Worry no more! because this article will help you.

In this article, we will discuss “Typeerror: object of type int64 is not json serializable”, provide the causes of this error, and give a solution to resolve the error.

First, let us understand what this error means.

What is “Typeerror: object of type int64 is not json serializable”?

“TypeError: object of type ‘int64’ is not JSON serializable” is a Python error message that appears when you attempt to serialize an object of type ‘int64’ to JSON format.

This is because JSON only supports limited data types, such as strings, numbers, booleans, arrays, and objects.

The int64 data type is not included.

JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format used for transmitting data between a server and a client in web applications.

JSON supports a limited set of data types, such as strings, numbers, booleans, arrays, and objects.

However, it does not support NumPy data types such as ‘int64’, ‘float64’, etc.

Numpy

NumPy is a Python library used for working with arrays and numerical operations.

It provides its own data types, such as int64, float64, etc., which are more efficient than the built-in Python data types

However, these data types are not compatible with JSON serialization.

Int64

‘Int64’ is a data type from the NumPy library.

It is used for numerical computations and provides a higher level of precision than the built-in Python ‘int’ type.

Why Typeerror: object of type int64 is not json serializable occurs?

The error message “TypeError: Object of type int64 is not JSON serializable” typically occurs when you try to serialize a NumPy int64 object to a JSON string.

This error message means that the object cannot be converted to a JSON format.

Here is the Python code snippet that demonstrates the “TypeError: object of type ‘int64’ is not JSON serializable” error:

import json
import numpy as np
Amount = np.power(5, 3, dtype=np.int64)
json_str = json.dumps({'Amount': Amount})
print(json_str)

In this example, we use the Numpy Library to create an ‘int64’ object called “Amount”.

Then we attempt to convert ‘Amount’ object to a string using the ‘json.dumps()’ function.

However, since ‘int64’ is not a JSON-serializable data type, this results in an error message:

TypeError: Object of type int64 is not JSON serializable

Now let us know how to fix this error.

How to fix Typeerror: object of type int64 is not json serializable?

Here are the alternative solutions that you can use to solve “Typeerror: object of type int64 is not json serializable”:

Solution 1: Use the built-in Python ‘int’ or ‘float’ classes:

The first way to solve the error is to use the built-in Python ‘int’ or ‘float’ classes to convert the ‘int64’ object to a JSON-serializable data type.

These classes are compatible with JSON and can represent numerical values in a JSON-serializable format.

Here is the updated code for the example problem above:

import json
import numpy as np
Amount = np.power(5, 3, dtype=np.int64)
json_str = json.dumps({'Amount': int(Amount)})
print(json_str)

In this updated code, the ‘Amount’ object is first converted to a Python ‘int’ using the ‘int()’ function before being passed to the ‘json.dumps()’ function.

This ensures that the ‘Amount’ object is in a JSON-serializable format.

Output

{"Amount": 125}

Similarly, you can convert the ‘int64’ object to a Python ‘float’ using the ‘float()‘ function.

If you need to represent decimal values in a JSON-serializable format.

Solution 2: Extending the JSONEncoder class:

Extending the JSONEncoder class can also be used to solve the “TypeError: object of type ‘int64’ is not JSON serializable” error in Python.

The JSONEncoder class is part of the ‘json’ module in Python.

It provides a way to define custom encoding rules for JSON-serializable objects.

By extending the JSONEncoder class and defining custom encoding rules for ‘int64’ objects.

You can serialize them to a JSON string without encountering the “TypeError” error.

Here is another updated code for the example problem above:

import json
import numpy as np

class Int64Encoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.int64):
            return int(obj)
        return super(Int64Encoder, self).default(obj)

Amount = np.power(1000, 26, dtype=np.int64)
json_str = json.dumps({'Amount': Amount}, cls=Int64Encoder)
print(json_str)

In this updated code, we define a custom JSONEncoder class called ‘Int64Encoder‘ that checks if the object being serialized is an ‘int64‘ object.

If it is, it converts the object to a Python ‘int‘ using the ‘int()‘ function before encoding it to JSON.

If the object is not an ‘int64‘ object, it passes the object to the parent class to encode it using the default rules.

To use the custom encoder, we pass it as the ‘cls‘ argument to the ‘json.dumps()‘ function.

This tells the function to use our custom ‘Int64Encoder‘ class to encode the ‘Amount‘ object.

Output:

{"Amount": 125}

By extending the JSONEncoder class, we can define custom encoding rules for any non-JSON-serializable object.

Which makes it a powerful tool for working with complex data types in Python.

Solution 3: Use the ‘default’ keyword argument:

Another way to solve the error is to use the ‘default‘ keyword argument of the ‘json.dumps()’ function.

The ‘default‘ keyword argument is a callable that will be called for objects that are not JSON-serializable.

By providing a callable that converts ‘int64‘ objects to a JSON-serializable format, we can avoid the “TypeError” error.

Here’s an example of how to use the ‘default’ keyword argument to serialize ‘int64’ objects to a JSON string:

import json
import numpy as np

Amount = np.power(5, 3, dtype=np.int64)

json_str = json.dumps({'Amount': Amount}, default=lambda x: int(x) if isinstance(x, np.int64) else None)

print(json_str)

In this example, we pass a lambda function as the ‘default‘ argument to the ‘json.dumps()‘ function.

The lambda function checks if the object being serialized is an ‘int64‘ object, and if it is, it converts it to a Python ‘int‘ using the ‘int()‘ function.

If the object is not an ‘int64‘ object, the lambda function returns ‘None‘, which tells the ‘json.dumps()‘ function to use its default encoding rules.

Output:

{"Amount": 125}

By using the ‘default‘ keyword argument, we can handle any non-JSON-serializable objects in a flexible and customizable way.

This approach can be useful when dealing with complex data types that require custom encoding rules.

So those are the alternative solutions that you can use to fix “Typeerror: object of type int64 is not json serializable”.

I hope one or more of them helps you to fix your problem regarding the TypeError.

Here are the other fixed Python errors that you can visit, you might encounter them in the future.

Conclusion

In conclusion, in this article, we discuss “Typeerror: object of type int64 is not json serializable”, provide its causes, and give solutions that resolve the error.

By following the given solution, surely you can fix the error quickly and proceed to your coding project again.

I hope this article helps you to solve your problem regarding a Typeerror stating “object of type int64 is not json serializable”.

We’re happy to help you.

Happy coding! Have a Good day and God bless.