Skip to content
Advertisement

How to model an empty dictionary in pydantic

I’m working with a request of a remote webhook where the data I want to validate is either there, or an empty dictionary. I would like it to run through the model validator if it’s there but also not choke if it’s an empty dictionary.

input 1:

JavaScript

input 2:

JavaScript

input 3:

JavaScript
JavaScript

How would I model something like this in Pydantic such that inputs 1 and 2 succeed while input 3 fails?

Advertisement

Answer

Use extra = "forbid" option to disallow extra fields and use an empty model to represent an empty dictionary.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement