user13841758
user13841758

Reputation:

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?

Upvotes: 0

Views: 2625

Answers (1)

larsks
larsks

Reputation: 311298

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:

  • I've modified data so that it's valid JSON data.
  • I've removed the many=True from the call to MyResponseSchema() because you've edited your question such that you're no longer trying to parse a list of objects.

Upvotes: 0

Related Questions