TypeError: Python object is not JSON serializable

前端 未结 3 956
慢半拍i
慢半拍i 2021-01-04 23:58

I am trying to encode an object into json using json.dumps() in Django, however when I pass in a python object, it raises this error.

TypeError         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-05 00:31

    If you do invite.__dict__, it's going to give you a dictionary of all data related to one invite object. However, the dict's values are not necessarily primitive types, but objects as well(ModelState is just one of them). Serializing that would not only not working because json doesn't accept python objects, but you could also serialize a lot of meta data that's not used.

    Check out json official website to see what data types are json serializable. The fix would be either using django model serializer, or manually create a dict that in compliance to json format.

提交回复
热议问题