Skip to content

Commit c5e9a10

Browse files
authored
fix: dbjson serialization with most compact JSON representation (#299)
1 parent 4b84e4a commit c5e9a10

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

db_dtypes/json.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,9 @@ def _serialize_json(value):
143143
else:
144144
# `sort_keys=True` sorts dictionary keys before serialization, making
145145
# JSON comparisons deterministic.
146-
return json.dumps(value, sort_keys=True)
146+
# `separators=(',', ':')` eliminate whitespace to get the most compact
147+
# JSON representation.
148+
return json.dumps(value, sort_keys=True, separators=(",", ":"))
147149

148150
@staticmethod
149151
def _deserialize_json(value):

tests/compliance/json/test_json_compliance.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ def test_astype_str(self, data):
3131
# Use `json.dumps(str)` instead of passing `str(obj)` directly to the super method.
3232
result = pd.Series(data[:5]).astype(str)
3333
expected = pd.Series(
34-
[json.dumps(x, sort_keys=True) for x in data[:5]], dtype=str
34+
[json.dumps(x, sort_keys=True, separators=(",", ":")) for x in data[:5]],
35+
dtype=str,
3536
)
3637
tm.assert_series_equal(result, expected)
3738

@@ -46,7 +47,7 @@ def test_astype_string(self, data, nullable_string_dtype):
4647
# Use `json.dumps(str)` instead of passing `str(obj)` directly to the super method.
4748
result = pd.Series(data[:5]).astype(nullable_string_dtype)
4849
expected = pd.Series(
49-
[json.dumps(x, sort_keys=True) for x in data[:5]],
50+
[json.dumps(x, sort_keys=True, separators=(",", ":")) for x in data[:5]],
5051
dtype=nullable_string_dtype,
5152
)
5253
tm.assert_series_equal(result, expected)
@@ -119,11 +120,14 @@ class TestJSONArrayInterface(base.BaseInterfaceTests):
119120
def test_array_interface(self, data):
120121
result = np.array(data)
121122
# Use `json.dumps(data[0])` instead of passing `data[0]` directly to the super method.
122-
assert result[0] == json.dumps(data[0])
123+
assert result[0] == json.dumps(data[0], sort_keys=True, separators=(",", ":"))
123124

124125
result = np.array(data, dtype=object)
125126
# Use `json.dumps(x)` instead of passing `x` directly to the super method.
126-
expected = np.array([json.dumps(x) for x in data], dtype=object)
127+
expected = np.array(
128+
[json.dumps(x, sort_keys=True, separators=(",", ":")) for x in data],
129+
dtype=object,
130+
)
127131
# if expected.ndim > 1:
128132
# # nested data, explicitly construct as 1D
129133
# expected = construct_1d_object_array_from_listlike(list(data))

0 commit comments

Comments
 (0)