Skip to content

Commit 88a43d8

Browse files
authored
BUG: Attributes skipped when serialising plain Python objects to JSON (#42768) (#42931)
1 parent fca1f7c commit 88a43d8

File tree

4 files changed

+31
-1
lines changed

4 files changed

+31
-1
lines changed

doc/source/whatsnew/v1.4.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,7 @@ I/O
262262
- Bug in :func:`read_excel` attempting to read chart sheets from .xlsx files (:issue:`41448`)
263263
- Bug in :func:`json_normalize` where ``errors=ignore`` could fail to ignore missing values of ``meta`` when ``record_path`` has a length greater than one (:issue:`41876`)
264264
- Bug in :func:`read_csv` with multi-header input and arguments referencing column names as tuples (:issue:`42446`)
265+
- Bug in :func:`Series.to_json` and :func:`DataFrame.to_json` where some attributes were skipped when serialising plain Python objects to JSON (:issue:`42768`, :issue:`33043`)
265266
-
266267

267268
Period

pandas/_libs/src/ujson/python/objToJSON.c

-1
Original file line numberDiff line numberDiff line change
@@ -927,7 +927,6 @@ int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc) {
927927

928928
GET_TC(tc)->itemName = itemName;
929929
GET_TC(tc)->itemValue = itemValue;
930-
GET_TC(tc)->index++;
931930

932931
itemName = attr;
933932
break;

pandas/tests/io/json/test_pandas.py

+15
Original file line numberDiff line numberDiff line change
@@ -1769,3 +1769,18 @@ def test_to_json_multiindex_escape(self):
17691769
"\"(Timestamp('2017-01-23 00:00:00'), 'bar')\":true}"
17701770
)
17711771
assert result == expected
1772+
1773+
def test_to_json_series_of_objects(self):
1774+
class _TestObject:
1775+
def __init__(self, a, b, _c, d):
1776+
self.a = a
1777+
self.b = b
1778+
self._c = _c
1779+
self.d = d
1780+
1781+
def e(self):
1782+
return 5
1783+
1784+
# JSON keys should be all non-callable non-underscore attributes, see GH-42768
1785+
series = Series([_TestObject(a=1, b=2, _c=3, d=4)])
1786+
assert json.loads(series.to_json()) == {"0": {"a": 1, "b": 2, "d": 4}}

pandas/tests/io/json/test_ujson.py

+15
Original file line numberDiff line numberDiff line change
@@ -720,6 +720,21 @@ def my_obj_handler(_):
720720
ujson.encode(obj_list, default_handler=str)
721721
)
722722

723+
def test_encode_object(self):
724+
class _TestObject:
725+
def __init__(self, a, b, _c, d):
726+
self.a = a
727+
self.b = b
728+
self._c = _c
729+
self.d = d
730+
731+
def e(self):
732+
return 5
733+
734+
# JSON keys should be all non-callable non-underscore attributes, see GH-42768
735+
test_object = _TestObject(a=1, b=2, _c=3, d=4)
736+
assert ujson.decode(ujson.encode(test_object)) == {"a": 1, "b": 2, "d": 4}
737+
723738

724739
class TestNumpyJSONTests:
725740
@pytest.mark.parametrize("bool_input", [True, False])

0 commit comments

Comments
 (0)