Skip to content

Commit 184092b

Browse files
bolkedebruinWillAyd
andcommitted
Fix TypeError when pulling field that is None
If normalizing a jsonstruct a field can be set to None due to a schema change. Co-Authored-By: William Ayd <[email protected]>
1 parent 080e331 commit 184092b

File tree

3 files changed

+38
-3
lines changed

3 files changed

+38
-3
lines changed

doc/source/whatsnew/v1.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -803,6 +803,7 @@ I/O
803803
- Bug in :func:`read_json` where default encoding was not set to ``utf-8`` (:issue:`29565`)
804804
- Bug in :class:`PythonParser` where str and bytes were being mixed when dealing with the decimal field (:issue:`29650`)
805805
- :meth:`read_gbq` now accepts ``progress_bar_type`` to display progress bar while the data downloads. (:issue:`29857`)
806+
- Bug in :func:`pandas.io.json.json_normalize` where a missing value in the location specified by `record_path` would raise a ``TypeError`` (:issue:`30148`)
806807

807808
Plotting
808809
^^^^^^^^

pandas/io/json/_normalize.py

+13-3
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@
33

44
from collections import defaultdict
55
import copy
6-
from typing import DefaultDict, Dict, List, Optional, Union
6+
from typing import Any, DefaultDict, Dict, Iterable, List, Optional, Union
77

88
import numpy as np
99

1010
from pandas._libs.writers import convert_json_to_lines
1111

12+
import pandas as pd
1213
from pandas import DataFrame
1314

1415

@@ -228,14 +229,23 @@ def json_normalize(
228229
Returns normalized data with columns prefixed with the given string.
229230
"""
230231

231-
def _pull_field(js, spec):
232-
result = js
232+
def _pull_field(js: Dict[str, Any], spec: Union[List, str]) -> Iterable:
233+
result = js # type: ignore
233234
if isinstance(spec, list):
234235
for field in spec:
235236
result = result[field]
236237
else:
237238
result = result[spec]
238239

240+
if not isinstance(result, Iterable):
241+
if pd.isnull(result):
242+
result = [] # type: ignore
243+
else:
244+
raise TypeError(
245+
f"{js} has non iterable value {result} for path {spec}. "
246+
"Must be iterable or null."
247+
)
248+
239249
return result
240250

241251
if isinstance(data, list) and not data:

pandas/tests/io/json/test_normalize.py

+24
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,30 @@ def test_nested_flattening_consistent(self):
463463
# They should be the same.
464464
tm.assert_frame_equal(df1, df2)
465465

466+
def test_nonetype_record_path(self, nulls_fixture):
467+
# see gh-30148
468+
# should not raise TypeError
469+
result = json_normalize(
470+
[
471+
{"state": "Texas", "info": nulls_fixture},
472+
{"state": "Florida", "info": [{"i": 2}]},
473+
],
474+
record_path=["info"],
475+
)
476+
expected = DataFrame({"i": 2}, index=[0])
477+
tm.assert_equal(result, expected)
478+
479+
def test_non_interable_record_path_errors(self):
480+
# see gh-30148
481+
test_input = {"state": "Texas", "info": 1}
482+
test_path = "info"
483+
msg = (
484+
f"{test_input} has non iterable value 1 for path {test_path}. "
485+
"Must be iterable or null."
486+
)
487+
with pytest.raises(TypeError, match=msg):
488+
json_normalize([test_input], record_path=[test_path])
489+
466490

467491
class TestNestedToRecord:
468492
def test_flat_stays_flat(self):

0 commit comments

Comments
 (0)