Skip to content
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

squash __root__ in BaseModel json encoding #1524

Merged
merged 1 commit into from Jun 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions fastapi/encoders.py
Expand Up @@ -71,6 +71,8 @@ def jsonable_encoder(
by_alias=by_alias,
skip_defaults=bool(exclude_unset or skip_defaults),
)
if "__root__" in obj_dict:
obj_dict = obj_dict["__root__"]
return jsonable_encoder(
obj_dict,
exclude_none=exclude_none,
Expand Down
9 changes: 9 additions & 0 deletions tests/test_jsonable_encoder.py
Expand Up @@ -76,6 +76,10 @@ class ModelWithDefault(BaseModel):
bla: str = "bla"


class ModelWithRoot(BaseModel):
__root__: str


@pytest.fixture(
name="model_with_path", params=[PurePath, PurePosixPath, PureWindowsPath]
)
Expand Down Expand Up @@ -158,3 +162,8 @@ def test_encode_model_with_path(model_with_path):
else:
expected = "/foo/bar"
assert jsonable_encoder(model_with_path) == {"path": expected}


def test_encode_root():
model = ModelWithRoot(__root__="Foo")
assert jsonable_encoder(model) == "Foo"