How to flatten JSON objects in Python
In this post, we are going to learn about how to flatten JSON objects in Python. We will 2 methods that are available in Python.
Below are the two methods are given that we are going to use to flatten JSON objects:
- Using Recursion
- Using flatten_json library.
First, we have to know about JSON.
JSON:
- Expansion: JavaScript Object Notation.
- When there is a need for data transmission that takes place between a server and a web application, JSON can be used.
- It is a collection of key and value pairs.
Why flattening JSON objects?
When we need better understanding views, we can flatten JSON objects. After flattening, only key-value pairs will exist without nesting.
Method 1: Using Recursion
When compared to json-flatten library, this method is a little bit slower.
Let’s take a look at the example.
def flatteningJSON(b):
ans = {}
def flat(i, na =''):
#nested key-value pair: dict type
if type(i) is dict:
for a in i:
flat(i[a], na + a + '_')
#nested key-value pair: list type
elif type(i) is list:
j = 0
for a in i:
flat(a, na + str(j) + '_')
j += 1
else:
ans[na[:-1]] = i
flat(b)
return ans
unflattenJSON = {'user' :
{'Ram':
{'Roll_No':30,
'Marks': [90,100,78]
}
}
}
print("After flattening JSON object:")
print(flatteningJSON(unflattenJSON))
Output:
After flattening JSON object
{'user_Ram_Roll_No': 30, 'user_Ram_Marks_0': 90, 'user_Ram_Marks_1': 100, 'user_Ram_Marks_2': 78}Method: Using flatten_json library
This library has methods that can be used to flatten a JSON object to single key-value pairs and vice versa.
Installation:
pip install flatten_json
First, we imported the flatten_json library. Then we used a flatten() method which can be used to flatten a given JSON object.
- Syntax: flatten(JSON obj)
Now, we have a look at the program.
from flatten_json import flatten
unflattenJSON = {'user' :
{'Ram':
{'Roll_No':30,
'Marks': [90,100,78]
}
}
}
flattenJSON = flatten(unflattenJSON)
print("After flattening JSON object:")
print(flattenJSON)
Output:
After flattening JSON object:
{'user_Ram_Roll_No': 30, 'user_Ram_Marks_0': 90, 'user_Ram_Marks_1': 100, 'user_Ram_Marks_2': 78}So, I hope that you guys learned something new and useful from this tutorial.
Also read,
Leave a Reply