I currently have the following:
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
So I would like to return JSON in the format:
{
"mainErrorCode" : 1024,
"message" : "Validation Failed",
"errors" : [
{
"field" : "first_name",
"message" : "First name cannot have fancy characters"
},
{
"field" : "password",
"message" : "Password cannot be blank"
}
]
}
Currently I am getting the error:
TypeError: <errors.Error instance at 0x329b908> is not JSON serializable
I am using Flask's Jsonify.
return jsonify(errors=mainError.serialize())
I'm guessing that the list is causing the issue. Could someone please help me with the right way of going about this?
PS: There might be some other glaring errors in my approach (I'm quite new to Python =/)
Updated Solution
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
}
serializeis module level)? Also, what's the relation (or heirarchy) betweenErrorandMainErrorand how is it enforced?MainError. I'm not sure though.module. TheMainErrorobject will contain a list (errorsList) ofErrorobjects.