From: Muhammad Bin Gulzar <75139794+MBGrao@users.noreply.github.com> Date: Tue, 28 Jul 2026 12:28:18 +0000 (+0500) Subject: 🐛 Fix `exclude_defaults` not propagated to dict keys and values in `jsonable_encoder... X-Git-Tag: 0.140.9~2 X-Git-Url: http://git.ipfire.org/gitweb/?a=commitdiff_plain;h=aadfcce76380ab169fe172d5cda21722e53c4924;p=thirdparty%2Ffastapi%2Ffastapi.git 🐛 Fix `exclude_defaults` not propagated to dict keys and values in `jsonable_encoder` (#16043) Co-authored-by: Sebastián Ramírez --- diff --git a/fastapi/encoders.py b/fastapi/encoders.py index c9f882d2ba..e578768dac 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -299,6 +299,7 @@ def jsonable_encoder( key, by_alias=by_alias, exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, @@ -307,6 +308,7 @@ def jsonable_encoder( value, by_alias=by_alias, exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index 8f8bd3fcbb..96dc49a683 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -202,6 +202,20 @@ def test_encode_model_with_default(): } +def test_encode_model_with_default_in_dict_and_list(): + model = ModelWithDefault(foo="foo", bar="bar") + assert jsonable_encoder([model], exclude_defaults=True) == [{"foo": "foo"}] + assert jsonable_encoder({"key": model}, exclude_defaults=True) == { + "key": {"foo": "foo"} + } + assert jsonable_encoder({"key": [model]}, exclude_defaults=True) == { + "key": [{"foo": "foo"}] + } + assert jsonable_encoder({"key": model}) == { + "key": {"foo": "foo", "bar": "bar", "bla": "bla"} + } + + def test_custom_encoders(): class safe_datetime(datetime): pass