Open In App

Flattening JSON objects in Python

Last Updated : 01 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

JSON(JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modules, so there is no need to install it externally. A flatten json is nothing but there is no nesting is present and only key-value pairs are present. 

Example:

Unflattened JSON: {‘user’ :{‘Rachel’:{‘UserID’:1717171717, ‘Email’: ‘rachel1999@gmail.com’, ‘friends’: [‘John’, ‘Jeremy’, ‘Emily’]}}} Flattened JSON: {‘user_Rachel_friends_2’: ‘Emily’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘rachel1999@gmail.com’, ‘user_Rachel_friends_1’: ‘Jeremy’}

Need of flattening JSON: There are many reasons for the need of flattening JSON, such as for a better and more understandable view that is there are only key-value pairs are present without any nesting. It also allows for context-specific security and constraints to be implemented in a readable but in a more verbose way.

Approach to flatten JSON:

There are many ways to flatten JSON. There is one recursive way and another by using the json-flatten library.

Approach 1: Recursive Approach

Now we can flatten the dictionary array by a recursive approach which is quite easy to understand. The recursive approach is a bit slower than using the json-flatten library.

Example: 

Python3




# for a array value of a key
unflat_json = {'user':
               {'Rachel':
                {'UserID': 1717171717,
                 'Email': 'rachel1999@gmail.com',
                 'friends': ['John', 'Jeremy', 'Emily']
                 }
                }
               }
 
# Function for flattening
# json
 
 
def flatten_json(y):
    out = {}
 
    def flatten(x, name=''):
 
        # If the Nested key-value
        # pair is of dict type
        if type(x) is dict:
 
            for a in x:
                flatten(x[a], name + a + '_')
 
        # If the Nested key-value
        # pair is of list type
        elif type(x) is list:
 
            i = 0
 
            for a in x:
                flatten(a, name + str(i) + '_')
                i += 1
        else:
            out[name[:-1]] = x
 
    flatten(y)
    return out
 
 
# Driver code
print(flatten_json(unflat_json))


Output:

{‘user_Rachel_friends_2’: ‘Emily’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘rachel1999@gmail.com’, ‘user_Rachel_friends_1’: ‘Jeremy’}

Approach 2: Using flatten_json library

The json-flatten library provides functions for flattening a JSON object to a single key-value pairs, and unflattening that dictionary back to a JSON object. Installing library In order to use the flatten_json library, we need to install this library. flatten_json can be installed by running the following command in the terminal.

pip install flatten_json

Example: 

Python3




from flatten_json import flatten
 
unflat_json = {'user':
               {'Rachel':
                {'UserID': 1717171717,
                 'Email': 'rachel1999@gmail.com',
                 'friends': ['John', 'Jeremy', 'Emily']
                 }
                }
               }
 
flat_json = flatten(unflat_json)
 
print(flat_json)


Output:

{‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘rachel1999@gmail.com’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_friends_1’: ‘Jeremy’, ‘user_Rachel_friends_2’: ‘Emily’}



Previous Article
Next Article

Similar Reads

Python | Grouped Flattening of list
The problem of flattening a list is quite common, but sometimes, we need to perform the flattening but in the grouped manner, i.e getting the sublists of size K and flatten them. This particular utility has use-cases in many domains including web-development and day-day programming as well. Let's discuss certain ways in which this can be done. Meth
6 min read
Python - Value List Key Flattening
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform pairing of each value of keys to extract the flattened dictionary. This kind of problem can have application in data domains. Lets discuss certain way in which this task can be performed. Method #1: Using loop This is brute way in which this task ca
7 min read
Python Program For Flattening A Multilevel Linked List
Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the below figure. You are given the head of the first level of the list. Flatten the lis
4 min read
Python Program For Flattening A Linked List
Given a linked list where every node represents a linked list and contains two pointers of its type: Pointer to next node in the main list (we call it 'right' pointer in the code below).Pointer to a linked list where this node is headed (we call it the 'down' pointer in the code below). All linked lists are sorted. See the following example 5 ->
4 min read
Encoding and Decoding Custom Objects in Python-JSON
JSON as we know stands for JavaScript Object Notation. It is a lightweight data-interchange format and has become the most popular medium of exchanging data over the web. The reason behind its popularity is that it is both human-readable and easy for machines to parse and generate. Also, it's the most widely used format for the REST APIs. Note: For
5 min read
How to compare JSON objects regardless of order in Python?
JSON is Java Script Object Notation. These are language independent source codes used for data exchange and are generally lightweight in nature. It acts as an alternative to XML. These are generally texts which can be read and written easily by humans and it is also easier for machines to parse JSON and generate results. JSON is being used primaril
2 min read
Extract Multiple JSON Objects from one File using Python
Python is extremely useful for working with JSON( JavaScript Object Notation) data, which is a most used format for storing and exchanging information. However, it can become challenging when dealing with multiple JSON objects stored within a single file. In this article, we will see some techniques to easily extract multiple JSON Objects from a fi
3 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Practice Tags :
three90RightbarBannerImg