diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 41c589d49..c4a8bcf76 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -375,19 +375,14 @@ def encode_dict( if key not in allowed_keys: continue - # use type() in, instead of isinstance - # we don't want to allow subclasses, they should be encoded still - if type(key) in primitive_types: - encoded_key = key - else: - encoded_key = encode_value( - key, - by_alias=by_alias, - exclude_unset=exclude_unset, - exclude_none=exclude_none, - custom_encoder=custom_encoder, - sqlalchemy_safe=sqlalchemy_safe, - ) + encoded_key = encode_value( + key, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, + ) encoded_value = encode_value( value, diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index e7e447c1d..6b1b744eb 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -95,11 +95,23 @@ def test_encode_dict_with_nonprimative_keys(): def __init__(self, value: str) -> None: self.value = value + def __eq__(self, other) -> bool: + return isinstance(other, CustomString) and self.value == other.value + + def __hash__(self): + return hash(self.value) + assert jsonable_encoder( {CustomString("foo"): "bar"}, custom_encoder={CustomString: lambda v: v.value} ) == {"foo": "bar"} +def test_encode_dict_with_custom_encoder_keys(): + assert jsonable_encoder( + {"foo": "bar"}, + custom_encoder={str: lambda v: "_" + v} + ) == {"_foo": "_bar"} + def test_encode_dict_with_sqlalchemy_safe(): obj = {"_sa_foo": "foo", "bar": "bar"}