Skip to content

Commit a7fd904

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 facd756 commit a7fd904

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

doc/source/whatsnew/v1.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -774,7 +774,7 @@ I/O
774774
- Bug in :func:`read_json` where default encoding was not set to ``utf-8`` (:issue:`29565`)
775775
- Bug in :class:`PythonParser` where str and bytes were being mixed when dealing with the decimal field (:issue:`29650`)
776776
- :meth:`read_gbq` now accepts ``progress_bar_type`` to display progress bar while the data downloads. (:issue:`29857`)
777-
-
777+
- 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`)
778778

779779
Plotting
780780
^^^^^^^^

pandas/io/json/_normalize.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -228,14 +228,17 @@ def json_normalize(
228228
Returns normalized data with columns prefixed with the given string.
229229
"""
230230

231-
def _pull_field(js, spec):
231+
def _pull_field(js: Dict, spec: Union[List, str]) -> List:
232232
result = js
233233
if isinstance(spec, list):
234234
for field in spec:
235235
result = result[field]
236236
else:
237237
result = result[spec]
238238

239+
if not isinstance(result, list):
240+
result = []
241+
239242
return result
240243

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

pandas/tests/io/json/test_normalize.py

+13
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,19 @@ 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+
df1 = json_normalize(
470+
[
471+
{"state": "Texas", "info": nulls_fixture},
472+
{"state": "Florida", "info": [{"i": 2}]},
473+
],
474+
record_path=["info"],
475+
)
476+
df2 = DataFrame({"i": 2}, index=[0])
477+
tm.assert_equal(df1, df2)
478+
466479

467480
class TestNestedToRecord:
468481
def test_flat_stays_flat(self):

0 commit comments

Comments
 (0)