pythonmarshmallowflask-marshmallow

Python Marshmallow validate schema for list of objects?


I am trying to call an API, and parse the results and then return the parsed results.

Here is my schema in marshmallow:

from marshmallow import Schema, fields, post_load
import json

class MyResponseDataSchema(Schema):
    path = fields.Str(required=False)
    content_match_count = fields.Int(required=False)


class MyResponseSchema(Schema):
    value = fields.List(
        fields.Nested(MyResponseDataSchema),
        required=False,
    )
data = '{value: [{"path" : "libs/shared/components/shortcuts/src/lib/shortcuts.component.ts", "content_match_count" : 3},{"path" : "libs/shared/components/shortcuts/src/lib/shortcuts.module.ts", "content_match_count" : 5}]}'
schema_data = MyResponseSchema(many=True).load(data)

What is wrong with my schema?


Solution

  • The problem here isn't with your schema, it's with your data. You're trying to load() a string, but Marshmallow doesn't work that way; you need to pass a dictionary to the .load() method:

    from marshmallow import Schema, fields
    import json
    
    class MyResponseDataSchema(Schema):
        path = fields.Str(required=False)
        content_match_count = fields.Int(required=False)
    
    
    class MyResponseSchema(Schema):
        value = fields.List(
            fields.Nested(MyResponseDataSchema),
            required=False,
        )
    
    data = '{"value": [{"path" : "libs/shared/components/shortcuts/src/lib/shortcuts.component.ts", "content_match_count" : 3},{"path" : "libs/shared/components/shortcuts/src/lib/shortcuts.module.ts", "content_match_count" : 5}]}'
    
    obj = json.loads(data)
    schema_data = MyResponseSchema().load(obj)
    

    This is shown in the Marshmallow documentation.

    Note that in the above code, I've made two changes from your example: