Skip to content

Series.to_json produces invalid JSON with orient="index" if index is multilevel #31028

Closed
@dargueta

Description

@dargueta

Code Sample, a copy-pastable example if possible

dataframe = pd.DataFrame({'x': [1, 2, 3], 'y': ['a', 'b', 'c']})
series = dataframe.stack()
print(series.to_json(orient="index"))

The keys in the output have unescaped quotes in them, resulting in invalid JSON. Output here is indented for clarity:

{
    "[0,"x"]": 1,
    "[0,"y"]": "a",
    "[1,"x"]": 2,
    "[1,"y"]": "b",
    "[2,"x"]": 3,
    "[2,"y"]": "c"
}

Problem description

to_json() should always either 1) produce valid JSON, or 2) throw an exception if it cannot.

Expected Output

The multilevel index in the output should be properly escaped to produce valid JSON, like so:

{
    "[0,\"x\"]": 1,
    "[0,\"y\"]": "a",
    "[1,\"x\"]": 2,
    "[1,\"y\"]": "b",
    "[2,\"x\"]": 3,
    "[2,\"y\"]": "c"
}

Output of pd.show_versions()

INSTALLED VERSIONS

commit : None
python : 3.7.3.final.0
python-bits : 64
OS : Darwin
OS-release : 18.7.0
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 0.25.3
numpy : 1.18.1
pytz : 2019.3
dateutil : 2.8.0
pip : 19.3.1
setuptools : 45.0.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : 2.8.4 (dt dec pq3 ext lo64)
jinja2 : 2.10.3
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 0.15.1
pytables : None
s3fs : 0.4.0
scipy : None
sqlalchemy : 1.3.12
tables : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    IO JSONread_json, to_json, json_normalizeNeeds InfoClarification about behavior needed to assess issueNeeds TestsUnit test(s) needed to prevent regressionsgood first issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions