Skip to content

BUG: to_json() swallows attributes of dataclasses #42768

Closed
@aberres

Description

@aberres

Code Sample, a copy-pastable example

from dataclasses import dataclass
import pandas as pd

@dataclass()
class MyObject:
    a: "str"
    b: "str"
    c: "str"

@dataclass()
class MyObject2:
    a: "str"
    _b: "str"
    c: "str"
        

o1 = MyObject(a='a', b='b', c='c')
o2 = MyObject2(a='a', _b='b', c='c')


df = pd.DataFrame({"objects":[o1, o2]})

print(df.to_json())
print(pd._libs.json.dumps(o1))
print(pd._libs.json.dumps(o2))

Output:

{"objects":{"0":{"a":"a","c":"c"},"1":{"a":"a"}}}
{"a":"a","c":"c"}
{"a":"a"}

Problem description

While the dataclasses have three attributes depending on the naming only one or two show up in the JSON dump.

Expected Output

{"objects":{"0":{"a":"a","b"="b","c":"c"},"1":{"a":"a","_b"="b","c":"c"}}}
{"a":"a","b"="b","c":"c"}
{"a":"a","_b"="b","c":"c"}

Output of pd.show_versions()

INSTALLED VERSIONS

commit : c7f7443
python : 3.9.1.final.0
python-bits : 64
OS : Darwin
OS-release : 20.5.0
Version : Darwin Kernel Version 20.5.0: Sat May 8 05:10:33 PDT 2021; root:xnu-7195.121.3~9/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.UTF-8

pandas : 1.3.1
numpy : 1.21.1
pytz : 2021.1
dateutil : 2.8.2
pip : 21.0.1
setuptools : 49.2.1
Cython : None
pytest : 6.2.4
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : 2.9.1 (dt dec pq3 ext lo64)
jinja2 : 2.11.3
IPython : 7.20.0
pandas_datareader: None
bs4 : 4.9.3
bottleneck : 1.3.2
fsspec : 2021.07.0
fastparquet : None
gcsfs : 2021.07.0
matplotlib : 3.3.4
numexpr : 2.7.3
odfpy : None
openpyxl : 3.0.7
pandas_gbq : 0.15.0
pyarrow : 4.0.1
pyxlsb : None
s3fs : None
scipy : 1.7.0
sqlalchemy : 1.4.22
tables : None
tabulate : 0.8.9
xarray : None
xlrd : 1.2.0
xlwt : None
numba : 0.51.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugIO JSONread_json, to_json, json_normalizeNeeds TriageIssue that has not been reviewed by a pandas team member

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions