Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python convert nested JSON list to excel file

I have a JSON flow file that I need to convert to an excel file within my code. My problem occurs because my JSON flow file has a nested list that then contains other items.

example_json_flow = {
    "flows": [
        {
            "item1": "item1 text example",
        },
        {
            "item2": 20,
        }
    ]
}

I’ve looked at this question and that method seems to be the "normal" way to do it and what most questions are advertising, but it does not account for nested list items. This solution is what is offered in most questions related to this issue. But it puts everything in one single column in excel, which is not what I am looking for. The method that is explained uses pandas as seen below

df = pandas.read_json(self.open_file_browser_json())
df.to_excel("testing_this.xlsx", index=False)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To convert the nested JSON list to an Excel file, you can use the json_normalize() function from the pandas library to flatten the nested JSON list, and then write it to an Excel file using the to_excel() function.

Here’s an example code snippet that you can use:

import pandas as pd

example_json_flow = {
    "flows": [
        {
            "item1": "item1 text example",
            "list1": [
                {"item3": "item3 text example"},
                {"item4": 40}
            ]
        },
        {
            "item2": 20,
            "list2": [
                {"item5": "item5 text example"},
                {"item6": 60}
            ]
        }
    ]
}

df = pd.json_normalize(example_json_flow, record_path=['flows'], meta= 
['flows'])
df.to_excel("output.xlsx", index=False)

In this example, the json_normalize() function is used to flatten the flows key in the example_json_flow dictionary. The record_path parameter is used to specify the key that contains the nested list items, which are list1 and list2 in this case. The meta parameter is used to include the original flows dictionary as a column in the resulting DataFrame.

Once the DataFrame is created, you can use the to_excel() function to write it to an Excel file. The index=False parameter is used to exclude the index column from the output.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading