-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add Types that needs to be parsed from strings. #195
Comments
there's been no progress because I haven't needed it and no one else has asked for it. I think it's a pretty rare case and would probably be best implemented as a validator. |
I need it! The issue is that I have to handle a config which is passed as a {
"key_a": "42",
"key_b": "[1, 2, 3]"
} Ideally, I can apply key_b = Field(List[int])
key_b.parse("[1, 2, 3]") |
As I say, much easier to user a validator, then all the subsiquent validation logic should work as normal. import json
from typing import List
from pydantic import BaseModel, validator
class SubModel(BaseModel):
foo: int
bar: List[int]
class Model(BaseModel):
foobar: SubModel
@validator('foobar', pre=True)
def to_json(cls, v):
try:
return json.loads(v)
except ValueError as e:
raise ValueError('foobar value was not valid json') from e
d = Model(foobar='{"foo": 1, "bar": [1,2,3]}')
print(d.dict())
try:
Model(foobar='{"foo": 1, "bar": [1,2,"x"]}')
except Exception as e:
print(e)
try:
Model(foobar='{"foo": 1, "bar": not json}')
except Exception as e:
print(e) outputs:
|
Thanks, I hadn't thought about This is essentially what I wanted: class MyModel(BaseModel):
key_a: int
key_b: List[int]
@validator('key_b', pre=True, whole=True)
def _b_as_json(cls, v):
return json.loads(v)
print(MyModel(**{
"key_a": "42",
"key_b": "[1, 2, 3]"
})) I still like the idea of receiving a parser by just specifying things like |
I guess the best solutions is would be a PR welcome. |
Sometimes data needs to be parsed recursively.
Partly taken from:
https://github.com/samuelcolvin/pydantic/blob/3ef595556cfc1b98d97be84f259091aa1568da3a/pydantic/types.py#L321
Is there any progress or plans to implement this?
Edit:
On a second thought, maybe something like this is more flexible:
The text was updated successfully, but these errors were encountered: