0
votes

I couldn't read this specific Json file properly as a Pandas Dataframe. I've used similar code for the rest of other JSON samples - which works perfectly, however I need some help in understanding what could be wrong here.

The nested "traits" cannot be read directly and throws an error. The actual table looks like this:

Table Sample

import json 
import pandas as pd 
from pandas.io.json import json_normalize

with open("./assessment/0144209a-32ee-4114-bc69-9912dd3dde5c.json") as f:
    d = json.load(f)

df = json_normalize(d['results'])
df.head(10)

works_data = json_normalize(data=data['results'], record_path='traits')
works_data.head()

--------------------------------------------------------------------------- KeyError Traceback (most recent call last) in () ----> 1 works_data = json_normalize(data=data['results'], record_path='traits') 2 works_data.head()

C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\json\normalize.py in json_normalize(data, record_path, meta, meta_prefix, record_prefix, errors, sep) 257 records.extend(recs) 258 --> 259 _recursive_extract(data, record_path, {}, level=0) 260 261 result = DataFrame(records)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\json\normalize.py in _recursive_extract(data, path, seen_meta, level) 233 else: 234 for obj in data: --> 235 recs = _pull_field(obj, path[0]) 236 237 # For repeating the metadata later

C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\json\normalize.py in _pull_field(js, spec) 180 result = result[field] 181 else: --> 182 result = result[spec] 183 184 return result

KeyError: 'traits'

1
Provide data as text - Smart Manoj
May I know if I should pass it as String and if yes, how ? - Dinesh Muniandy

1 Answers

1
votes

Looks like a small syntax error in the variable name. You included data instead of d on row 11. Switch the following:

data=data['results']

To this:

data=d['results']