Repository: pandas-dev/pandas

Issue:
json_normalize does not normalize subrecords properly if any subrecords values are NoneType
### Code Sample, a copy-pastable example if possible

```python
data_fail_to_normalize = \
        [{'info': None}, 
         
        {'info': 
         {'created_at': '11/08/1993', 'last_updated': '26/05/2012'},
        'author_name': 
         {'first': 'Jane', 'last_name': 'Doe'}
        }]

data_partial_fail = \
        [{'info': None, 
         'author_name': 
         {'first': 'Smith', 'last_name': 'Appleseed'}
        }, 
        
        {'info': 
         {'created_at': '11/08/1993', 'last_updated': '26/05/2012'},
        'author_name': 
         {'first': 'Jane', 'last_name': 'Doe'}
        }]

>>> import pandas as pd
>>> pd.io.json.json_normalize(data_fail_to_normalize)
```
#### Output 1
|    | author_name                           | info                                                       |
|---:|:--------------------------------------|:-----------------------------------------------------------|
|  0 | nan                                   |                          None                              |
|  1 | {'first': 'Jane', 'last_name': 'Doe'} | {'created_at': '11/08/1993', 'last_updated': '26/05/2012'} |

```python
>>> pd.io.json.json_normalize(data_partial_fail)
```
#### Output 2
|    | author_name.first   | author_name.last_name   |   info | info.created_at   | info.last_updated   |
|---:|:--------------------|:------------------------|-------:|:------------------|:--------------------|
|  0 | Smith               | Appleseed               |    nan | nan               | nan                 |
|  1 | Jane                | Doe                     |    nan | 11/08/1993        | 26/05/2012          |

### Problem description
I expected that the json_normalize function takes into account the presence of NoneTypes in the dictionaries. This leads to 2 separate issues (If I should open this as 2 separate issues, let me know). 

I have already written a fix that solves this issue - if anyone else can validate that this is not working as intended, I can set up a PR.

#### Output 1
Does not unnest json after encountering NoneType at first instance of subrecord, line 192 of [`pandas/io/json/normalize.py`](https://github.com/pandas-dev/pandas/blob/a00154dcfe5057cb3fd86653172e74b6893e337d/pandas/io/json/normalize.py#L192)

#### Output 2
Keeps the None value when encountered, [{k: {'alpha': 'foo', 'beta': 'bar'}}, {k: None}], see [`nested_to_record`](https://github.com/pandas-dev/pandas/blob/a00154dcfe5057cb3fd86653172e74b6893e337d/pandas/io/json/normalize.py#L24) function. Creates additional column of `nan`s which would not otherwise occur if that particular key was removed.

### Expected Output
#### Output 1
|    | author_name.first   | author_name.last_name   | info.created_at   | info.last_updated   |
|---:|:--------------------|:------------------------|:------------------|:--------------------|
|  0 | nan                 | nan                     | nan               | nan                 |
|  1 | Jane                | Doe                     | 11/08/1993        | 26/05/2012          |

#### Output 2
|    | author_name.first   | author_name.last_name   | info.created_at   | info.last_updated   |
|---:|:--------------------|:------------------------|:------------------|:--------------------|
|  0 | Smith               | Appleseed               | nan               | nan                 |
|  1 | Jane                | Doe                     | 11/08/1993        | 26/05/2012          |

#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit: None
python: 3.6.4.final.0
python-bits: 64
OS: Linux
OS-release: 4.4.0-104-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: en_US.UTF-8
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.22.0
pytest: None
pip: 9.0.1
setuptools: 38.4.0
Cython: None
numpy: 1.13.1
scipy: None
pyarrow: None
xarray: None
IPython: 6.2.1
sphinx: None
patsy: None
dateutil: 2.6.1
pytz: 2017.3
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 2.1.2
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: 1.0.1
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None
</details>



Discussion:
I would personally prefer the second option.  Feel free to post the PR!
@gfyoung Were you referring to opening this as two separate issues?
@aerymilts : I was referring to the second output being preferable to the first.

Resolving patch:
diff --git a/pandas/io/json/normalize.py b/pandas/io/json/normalize.py
--- a/pandas/io/json/normalize.py
+++ b/pandas/io/json/normalize.py
@@ -80,6 +80,8 @@ def nested_to_record(ds, prefix="", sep=".", level=0):
                 if level != 0:  # so we skip copying for top level, common case
                     v = new_d.pop(k)
                     new_d[newkey] = v
+                if v is None:  # pop the key if the value is None
+                    new_d.pop(k)
                 continue
             else:
                 v = new_d.pop(k)
@@ -189,7 +191,8 @@ def _pull_field(js, spec):
         data = [data]
 
     if record_path is None:
-        if any(isinstance(x, dict) for x in compat.itervalues(data[0])):
+        if any([[isinstance(x, dict)
+                for x in compat.itervalues(y)] for y in data]):
             # naive normalization, this is idempotent for flat records
             # and potentially will inflate the data considerably for
             # deeply nested structures:


Test patch:
diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py
--- a/pandas/tests/io/json/test_normalize.py
+++ b/pandas/tests/io/json/test_normalize.py
@@ -54,6 +54,17 @@ def state_data():
          'state': 'Ohio'}]
 
 
+@pytest.fixture
+def author_missing_data():
+    return [
+        {'info': None},
+        {'info':
+            {'created_at': '11/08/1993', 'last_updated': '26/05/2012'},
+            'author_name':
+         {'first': 'Jane', 'last_name': 'Doe'}
+         }]
+
+
 class TestJSONNormalize(object):
 
     def test_simple_records(self):
@@ -226,6 +237,23 @@ def test_non_ascii_key(self):
         result = json_normalize(json.loads(testjson))
         tm.assert_frame_equal(result, expected)
 
+    def test_missing_field(self, author_missing_data):
+        # GH20030: Checks for robustness of json_normalize - should
+        # unnest records where only the first record has a None value
+        result = json_normalize(author_missing_data)
+        ex_data = [
+            {'author_name.first': np.nan,
+             'author_name.last_name': np.nan,
+             'info.created_at': np.nan,
+             'info.last_updated': np.nan},
+            {'author_name.first': 'Jane',
+             'author_name.last_name': 'Doe',
+             'info.created_at': '11/08/1993',
+             'info.last_updated': '26/05/2012'}
+        ]
+        expected = DataFrame(ex_data)
+        tm.assert_frame_equal(result, expected)
+
 
 class TestNestedToRecord(object):
 
@@ -322,3 +350,28 @@ def test_json_normalize_errors(self):
                             ['general', 'trade_version']],
                       errors='raise'
                       )
+
+    def test_nonetype_dropping(self):
+        # GH20030: Checks that None values are dropped in nested_to_record
+        # to prevent additional columns of nans when passed to DataFrame
+        data = [
+            {'info': None,
+             'author_name':
+             {'first': 'Smith', 'last_name': 'Appleseed'}
+             },
+            {'info':
+                {'created_at': '11/08/1993', 'last_updated': '26/05/2012'},
+             'author_name':
+                {'first': 'Jane', 'last_name': 'Doe'}
+             }
+        ]
+        result = nested_to_record(data)
+        expected = [
+            {'author_name.first': 'Smith',
+             'author_name.last_name': 'Appleseed'},
+            {'author_name.first': 'Jane',
+             'author_name.last_name': 'Doe',
+             'info.created_at': '11/08/1993',
+             'info.last_updated': '26/05/2012'}]
+
+        assert result == expected