我目前有以下内容:
class MainError:
def __init__(self, code, message, errorsList):
self.code = code
self.message = message
# List of Error objects
self.errorsList = errorsList
def serialize(self):
return {
'mainErrorCode': self.code,
'message': self.message,
'errors': self.errorsList
}
class Error:
def __init__(self, field, message):
self.field = field
self.message = message
所以我想以格式返回JSON
:
{
"mainErrorCode" : 1024,
"message" : "Validation Failed",
"errors" : [
{
"field" : "first_name",
"message" : "First name cannot have fancy characters"
},
{
"field" : "password",
"message" : "Password cannot be blank"
}
]
}
目前我收到错误:
TypeError: <errors.Error instance at 0x329b908> is not JSON serializable
我正在使用Flask's
Jsonify
。
return jsonify(errors=mainError.serialize())
我猜测list
导致了这个问题。有人可以用正确的方式帮我解决这个问题吗?
更新了解决方案
def serialize(self):
return {
'mainErrorCode': self.code,
'message': self.message,
'errors': [error.serialize() for error in self.errorsList]
}
class Error:
def __init__(self, field, message):
self.field = field
self.message = message
def serialize(self):
return {
'field': self.field,
'message': self.message
}
答案 0 :(得分:3)
如错误所示,您有一个不可序列化的Error
个对象列表。所以让它们可序列化:
class Error:
def __init__(self, field, message):
self.field = field
self.message = message
def serialize(self):
return {
'field': self.field,
'message': self.message
}