JSON with multiple levels
In this case, the nested JSON data contains another JSON object as the value for some of its attributes. This makes the data multi-level and we need to flatten it as per the project requirements for better readability, as explained below.
Python3
# 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' } } } |
Here, the data contains multiple levels. To convert it to a dataframe we will use the json_normalize() function of the pandas library.
Python3
pd.json_normalize(data) |
Output:
Here, we see that the data is flattened and converted to columns. If we do not wish to completely flatten the data, we can use the max_level attribute as shown below.
Python3
pd.json_normalize(data,max_level = 0 ) |
Output:
Here, we see that the info column is not flattened further.
Python3
pd.json_normalize(data,max_level = 1 ) |
Output:
Here, we see that the contacts column is not flattened further.
Converting nested JSON structures to Pandas DataFrames
In this article, we are going to see how to convert nested JSON structures to Pandas DataFrames.