Python return json.dumps got error : TypeError: Object of type int32 is not JSON serializable

Question:

i want to return list like this example in json [[28, 73, 59, 29], [25, 58, 51, 25], [17, 60, 51, 25], []]

‘temp_list_area_lips’ is contain my data list what i want to send using "listAreaLips": list_area_lips in json.dumps.

my code is like this :

list_area_lips = temp_list_area_lips
print("bbbb", list_area_lips, "aaaa - ", type(list_area_lips))

return json.dumps({"faceDetected": face_detected, "listFaceUrl": list_face_url, "listFaceCategory":      list_face_category, "listAreaLips": list_area_lips})

but it return error ‘TypeError: Object of type int32 is not JSON serializable’ like the image below
1
2

but if i assign list_area_lips manually like the code below, it can send data safely

list_area_lips = [[28, 73, 59, 29], [25, 58, 51, 25], [17, 60, 51, 25], []]
print("bbbb", list_area_lips, "aaaa - ", type(list_area_lips))
return json.dumps({"faceDetected": face_detected, "listFaceUrl": list_face_url, "listFaceCategory":      list_face_category, "listAreaLips": list_area_lips})

so i check the data which i assign from variable and manually, but there is no difference type, the result like the image below

3

how to send data list like this : [[28, 73, 59, 29], [25, 58, 51, 25], [17, 60, 51, 25], []] in return json.dumps? thankyouu

Asked By: KEZIA ANGELINE

||

Answers:

As Brian pointed out, you’re trying to encode numpy instances which aren’t serializable. IMO The easiest way forward is to add a custom JSONEncoder to your application.

class NumpyArrayEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        else:
            return super().default(obj)
...

json.dumps(data, cls=NumpyArrayEncoder)

If you need to do this for flask, the implementation is similar:

from flask import Flask
from flask.json.provider import DefaultJSONProvider


class NumpyArrayEncoder(DefaultJSONProvider):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        else:
            return super().default(obj)


class CustomizedFlask(Flask):
    json_provider_class = NumpyArrayEncoder

...

app = CustomizedFlask()
Answered By: flakes
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.