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
Cannot parse nested object with custom root type #2100
Comments
Hello @sohama4 To support this we could add this logic directly
I run the benchmark and it doesn't seem to have any effect on the performance so the latter solution could be a good solution. @samuelcolvin WDYT? If you want to try it out already @sohama4 I would go with something like this import json
from typing import Any, Dict, List
from pydantic import BaseModel as PydanticBaseModel
from pydantic.utils import ROOT_KEY
class BaseModel(PydanticBaseModel):
def __init__(__pydantic_self__, **data: Any) -> None:
if __pydantic_self__.__custom_root_type__ and data.keys() != {ROOT_KEY}:
data = {ROOT_KEY: data}
super().__init__(**data)
... Hope it helps! |
@PrettyWood - thank you for the response, I will try it out soon, and will close this out ASAP. I think the docs must mention this behavior, so I left a comment on the PR you linked. |
Similar issue with respect to Worked this around like this: class BaseCustomRootModel(BaseModel):
@classmethod
def from_orm(cls, obj: Any):
if cls.__custom_root_type__:
class Wrapper:
__slots__ = ('__root__',)
def __init__(self, obj):
self.__root__ = obj
return super().from_orm(Wrapper(obj))
return super().from_orm(obj)
|
@scorpp What about this solution? It should work with everything above + orm if I'm not mistaken from pydantic import BaseModel as PydanticBaseModel
class BaseModel(PydanticBaseModel):
@classmethod
def validate(cls, value):
if cls.__custom_root_type__:
return cls.parse_obj(value)
return super().validate(value) |
@PrettyWood no, this doesn't work. in Also your option with overriding I think that my solution (or alike) should be incorporated into |
I've merged both #2237 and #2238, thanks so much @PrettyWood for working on this. I think we can simplify the interface as well as improve performance in v2, but these two fixes should provide all the functionality required here. |
Checks
Question
Output of
python -c "import pydantic.utils; print(pydantic.utils.version_info())"
:Hello, thank you for the library - I have used it in production across multiple applications now! I am trying to parse a JSON with a nested JSON needing a custom root type of
Dict
- but get an error as shown in the snippet. I tried to check thru old bugs and the fixes for them like #1253 and #1773 and verified that all fixes are already in the version of the code I have pulled, but still don't see the behavior fixed. Can someone help point what I'm doing wrong?Thanks!
Output:
The text was updated successfully, but these errors were encountered: