Search code examples
jsonpython-3.xpandasdataframejson-normalize

Json normalize an array of objects


i need some help to normalize a json structure and convert it to dataframe

this is my example:

# importing the libraries used
import pandas as pd

# initializing the data
data = {
    'company': 'XYZ pvt ltd',
    'location': 'London',
    'info': [
        {
            'president': 'Rakesh Kapoor',
            'contacts': {
                'email': 'contact@xyz.com',
                'tel': '9876543210'
            }
        },
        {
            'president': 'Julio Vasquez',
            'contacts': {
                'email': 'julio@test.com',
                'tel': '987987654'
            }
        }
    ]
}

print(pd.json_normalize(data))

and this the output:

enter image description here

What I have to do to see a table like:

enter image description here

The final idea is make some sql querys over the last table.

Regards


Solution

  • You could use record_path and meta parameters of json_normalize:

    out = pd.json_normalize(data, record_path=['info'], meta=['company', 'location'], record_prefix='info.')
    

    Output:

      info.president info.contacts.email info.contacts.tel      company location
    0  Rakesh Kapoor     contact@xyz.com        9876543210  XYZ pvt ltd   London
    1  Julio Vasquez      julio@test.com         987987654  XYZ pvt ltd   London