Skip to content

BUG: Raise ValueError for non-string columns in read_json orient='table' (GH19129) #61359

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions pandas/io/json/_table_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,11 @@ def parse_table_schema(json, precise_float: bool) -> DataFrame:
pandas.read_json
"""
table = ujson_loads(json, precise_float=precise_float)
fields = table["schema"]["fields"]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you replace other instances of table["schema"]["fields"] below with fields?


if any(not isinstance(field["name"], str) for field in fields):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if any(not isinstance(field["name"], str) for field in fields):
if not all(isinstance(field["name"], str) for field in fields):

NIt: IMO this reads a little clearer with me

raise ValueError("All column names must be strings when using orient='table'.")

col_order = [field["name"] for field in table["schema"]["fields"]]
df = DataFrame(table["data"], columns=col_order)[col_order]

Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/io/json/test_json_table_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,3 +881,24 @@ def test_read_json_table_orient_period_depr_freq(self, freq):
out = StringIO(df.to_json(orient="table"))
result = pd.read_json(out, orient="table")
tm.assert_frame_equal(df, result)

def test_read_json_table_non_string_column_names(self) -> None:
bad_json = json.dumps(
{
"schema": {
"fields": [
{"name": 0, "type": "integer"},
{"name": 1, "type": "string"},
],
"primaryKey": [],
"pandas_version": "1.0.0",
},
"data": [[1, "a"], [2, "b"]],
}
)

with pytest.raises(
ValueError,
match="All column names must be strings when using orient='table'",
):
pd.read_json(StringIO(bad_json), orient="table")
Loading