TypeError: Object of type xxx is not JSON serializable
Description of the problem
When importing the Python json package and calling the /dumps function, you may encounter a TypeError: Object of type xxx is not JSON serializable error, that is, you cannot serialize certain object formats.
method settle an issue
The default encoding function cannot encode many data types with custom serialization, so you can write your own Myencoder to inherit the
The details are as follows:
class MyEncoder(): def default(self, obj): if isinstance(obj, ): return int(obj) elif isinstance(obj, ): return float(obj) elif isinstance(obj, ): return () else: return super(MyEncoder, self).default(obj)
Then specify the use of the custom serialization method when calling /dumps
(data, cls=MyEncoder)
dict to json
def dict_to_json(dict_obj,name, Mycls = None): js_obj = (dict_obj, cls = Mycls, indent=4) with open(name, 'w') as file_obj: file_obj.write(js_obj)
json to dict
def json_to_dict(filepath, Mycls = None): with open(filepath,'r') as js_obj: dict_obj = (js_obj, cls = Mycls) return dict_obj
TypeError: Object of type ‘int64’ is not JSON serializable (orfloat32)
In the use of json format to save data, often encountered xxx is not JSON serializable, that is, unable to serialize some object format, I met is that I used numpy when using the np data format, write data, (data) failure, we can define their own serialization of specific types of objects
See below how to define and use customizations about the np data type.
1. First, inheritance, custom serialization methods.
class NpEncoder(): def default(self, obj): if isinstance(obj, ): return int(obj) elif isinstance(obj, ): return float(obj) elif isinstance(obj, ): return () else: return super(NpEncoder, self).default(obj)
2. use dumps method ( we can directly serialize the dict directly into a json object ) plus cls = NpEncoder, data can be normal serialization of the
(data, cls=NpEncoder)
Actually, it's very simple, customize a serialization method and then add cls=NpEncoder to dumps
summarize
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.