Skip to content

Commit 5937e9c

Browse files
ericapisaniclaude
andcommitted
fix(utils): Avoid double serialization of strings in safe_serialize
When serialize_item() already returns a string (for plain strings, callables, or objects with __dict__), skip json.dumps to prevent wrapping the value in extra quotes with escaped characters. Co-Authored-By: Claude <[email protected]>
1 parent da05b34 commit 5937e9c

2 files changed

Lines changed: 37 additions & 1 deletion

File tree

sentry_sdk/utils.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2005,7 +2005,11 @@ def serialize_item(
20052005

20062006
try:
20072007
serialized = serialize_item(data)
2008-
return json.dumps(serialized, default=str)
2008+
return (
2009+
json.dumps(serialized, default=str)
2010+
if not isinstance(serialized, str)
2011+
else serialized
2012+
)
20092013
except Exception:
20102014
return str(data)
20112015

tests/test_utils.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
exc_info_from_error,
3636
get_lines_from_file,
3737
package_version,
38+
safe_serialize,
3839
)
3940

4041

@@ -1062,5 +1063,36 @@ def fake_getlines(filename):
10621063
assert result == expected_result
10631064

10641065

1066+
def test_safe_serialize_plain_string():
1067+
assert safe_serialize("already a string") == "already a string"
1068+
1069+
1070+
def test_safe_serialize_json_string():
1071+
assert safe_serialize('{"key": "value"}') == '{"key": "value"}'
1072+
1073+
1074+
def test_safe_serialize_dict():
1075+
assert safe_serialize({"key": "value"}) == '{"key": "value"}'
1076+
1077+
1078+
def test_safe_serialize_callable():
1079+
def my_func():
1080+
pass
1081+
1082+
result = safe_serialize(my_func)
1083+
assert result.startswith("<function")
1084+
assert '"' not in result[:1] # no wrapping quotes from json.dumps
1085+
1086+
1087+
def test_safe_serialize_object():
1088+
class MyClass:
1089+
def __init__(self):
1090+
self.x = 1
1091+
1092+
result = safe_serialize(MyClass())
1093+
assert result.startswith("<MyClass")
1094+
assert '"' not in result[:1] # no wrapping quotes from json.dumps
1095+
1096+
10651097
def test_package_version_is_none():
10661098
assert package_version("non_existent_package") is None

0 commit comments

Comments
 (0)