Python has many built in libraries one of them is NumPy.When we want to work with arrays in python, we use NumPy and for working with the json data we use a built in function of python which is JSON. Now, if we want to convert a python object into json object we use the datatypes which are json serializable. If the data type is not json serializable it will show the error “Object of type int64 is not json serializable” . In this article, we will be discussing this error in detail, starting with the basics.
What is JSON Object and How to create JSON Object?
Represented by { curly braces, the JSON object is formed of a key and a value pair where key is shown as a string while the type of value is not fixed. Between key and value we have to write a colon : and the key-value pair are made distinct with the help of comma between each pair.
For example: See the code below
{
"student name": {
"Name": "Tom",
"Class": 12,
"Result": true
}
}
Here, “student name” is the Object where “Name”, “Class”, “Result” are the key. “Tom” (string), 12 (number) and true (boolean), are the value to the key .
Creating JSON Object.
In python, we have two methods for creating a JSON object which are dumps() and dump() method.
Method 1- dumps()
In this method, a python object is taken as the input where it converts the python object into json string.
import json
in_num= True
print("Entered value is:", in_num)
print("The data type of entered value is:", type(in_num))
out_num = json.dumps(in_num)
print("Result value:", out_num)
print("Result type :", type(out_num))
The output will be as following.
Entered value is: True
The data type of entered value is: class 'bool'
Result value: true
Result type : class 'str'
Process finished with exit code 0
Method 2 – dump()
In this method, a python object and the file object is taken as the primary and a secondary input. When the json.dump completes the task it creates a json object and add it to the file which shows the file object.
Objects and their Datatypes: JSON serializable
We have variety of datatypes in python but not all of them can be converted into JSON Object. The datatypes such as int, str, float, dict, list, bool(True, False), none can be converted to json object. Other than these datatypes if an object has a datatype it will be non json serializable hence will not get converted into JSON format.
1. list/tuple into array
2.True into true
3.False into false
4.None into null
5.dict into object
6.str into string
7.float/int into number
Origin of “Object of type int64 is not json serializable” error?
When we are converting a python object into a json object using the dumps() method the only condition which is to be considered is the datatype of the python object if it is not a serializable datatype, the program will give a type error. Here, int64 is a type of datatype which is created in the NumPy and we are using the JSON module whenever the program will run it will show us the error since the json module doesn’t know how to use this datatype.
import json
import numpy
in_num= numpy.int64(True)
print("Entered value is:", in_num)
print("The data type of entered value is:", type(in_num))
out_num = json.dumps(in_num)
print("Result value:", out_num)
print("Result type :", type(out_num))
The output will be as following.
C:\Users\uttka\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\uttka\PycharmProjects\pythonProject\python.py
Entered value is: 1
The data type of entered value is:
Traceback (most recent call last):
File "C:\Users\uttka\PycharmProjects\pythonProject\python.py", line 47, in
out_num = json.dumps(in_num)
File "C:\Users\uttka\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Users\uttka\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\uttka\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\uttka\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type int64 is not JSON serializable
Process finished with exit code 1
Methods to avoid this error.
The conversion of python object to json object can be made error free while using the modules such as numpy, pandas etc if some simple steps are followed.
By changing the numpy objects to the simple int or any other serializable object and then to the json object.
import json
import numpy
in_num= numpy.int64(True)
print("Entered value is:", in_num)
print("The data type of entered value is:", type(in_num))
out_num = json.dumps(int(in_num))
print("Result value:", out_num)
print("Result type :", type(out_num))
The output will be as following.
Entered value is: 1
The data type of entered value is: class 'numpy.int64'
Result value: 1
Result type : class 'str'
Or you can use a class that uses the JSONEncoder class and directly convert numpy objects to the serializable objects.
import json
import numpy
class EnNp(json.JSONEncoder):
def default(self, object):
if isinstance(object, numpy.integer):
return int(object)
if isinstance(object, numpy.floating):
return float(object)
if isinstance(object, numpy.ndarray):
return object.tolist()
return super(EnNp, self).default(object)
in_num = numpy.int64(45)
print("Entered value is:", in_num)
print("The data type of entered value is:", type(in_num))
out_num = json.dumps(in_num, cls=EnNp)
print("Result value:", out_num)
print("Result type :", type(out_num))
The output will be as following.
Entered value is: 45
The data type of entered value is: class 'numpy.int64'
Result value: 45
Result type : class 'str'
Conclusion
In this article, we have discussed briefly about the JSON module, we have created json objects using the dumps() and the dump() method. For the better understanding of the error the datatypes and the objects are explained so that the difference can be understood by the reader. If you use the simple int or any other data type to solve the error then you have to physically change each python object while in the encoder function you just have to pass the class and it will perform its function and solve the error.