简体   繁体   中英

Jsonify a list of custom objects

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
        }

As the error suggests, you have a list of Error objects that are not serializable. So make them serializable:

class Error:    

    def __init__(self, field, message):
        self.field = field
        self.message = message

    def serialize(self):  
        return {           
            'field': self.field, 
            'message': self.message
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM