Skip to content

BUG: pd.json_normalize doesn't work well if len(sep) != 1 #45021

Closed
@OneMoreSecond

Description

@OneMoreSecond

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the master branch of pandas.

Reproducible Example

import pandas as pd

# Raise an exception
pd.json_normalize({'': {'a': 1}}, sep='')

# Wrong output
pd.json_normalize({'a': {'b': 1}}, sep='SEP')
# Give SEPaSEPb

Issue Description

The pointed line is always true if len(sep) != 1

~/.local/lib/python3.8/site-packages/pandas/io/json/_normalize.py in _normalise_json(data, key_string, normalized_dict, separator)
    150                 # to avoid adding the separator to the start of every key
    151                 key_string=new_key
--> 152                 if new_key[len(separator) - 1] != separator
    153                 else new_key[len(separator) :],
    154                 normalized_dict=normalized_dict,

I modify the line locally as below, then the example can work as expected

if not new_key.startswith(separator)

Also commented in #40035

Expected Behavior

a
0 1

and

aSEPb
0 1

Installed Versions

INSTALLED VERSIONS

commit : 66e3805
python : 3.8.3.final.0
python-bits : 64
OS : Linux
OS-release : 3.10.0-1062.12.1.el7.x86_64
Version : #1 SMP Tue Feb 4 23:02:59 UTC 2020
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : C
LANG : zh_CN.UTF-8
LOCALE : None.None

pandas : 1.3.5
numpy : 1.20.3
pytz : 2021.1
dateutil : 2.8.1
pip : 21.2.4
setuptools : 57.0.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.1
IPython : 7.24.1
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.4.2
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : 1.7.0
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds TriageIssue that has not been reviewed by a pandas team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions