0

I'm trying to convert bjson structure to a schema in marshmallow library.

Below is the marshmallow schema:

class GeneSchema(Schema):
"""description of class"""

   id_entrez = fields.Integer(required = True, error_messages={'required': "The 'id_entrez' field is requeired."})
   symbol = fields.String()

   @validates('id_entrez')
   def validate_id_entrez(self, data):
       if data <= 0:
          raise ValidationError("The 'id_entrez' field must be greater than zero.")

Below is the bjson will be converted to schema:

[{"symbol": "VAMP4", "_id": {"$oid": "57ae3b175a945932fcbdf41d"}, "id_entrez": 8674}, {"symbol": "CCT5", "_id": {"$oid": "57ae3b175a945932fcbdf41e"}, "id_entrez": 22948}]

Note that the bjson has the "_id" as ObjectId - "$oid". This is because the result of the query using the mongodb.

Please, does anyone know why not be to convert from bjson to marshmallow schema correctly ?

Thank you all!

Community
  • 1
  • 1
Kadu
  • 343
  • 7
  • 17

2 Answers2

1

I don't know if this question is still valid, but I would like to show my solution, how to push an ObjectId to a Marshmallow schema:

I simply use the pre processing method pre_load to convert the ObjectId to a String:

@pre_load
def convert_objectid(self, in_data, **kwargs):
    if "_id" in in_data:
        in_data["_id"] = str(in_data["_id"])
    return in_data
Timo Mohr
  • 11
  • 1
0

You can still use your schema to parse MongoDB output, just ignore extra "_id" field. If on the other hand you do want to parse that "_id", just add extra non-required field in your schema.

Maxim Kulkin
  • 2,698
  • 22
  • 11