The json format you gave is wrong. There is no comma before the key named locationDetails. You can use json_normalize after you fix it.

df = pd.json_normalize(json_data,meta=['lossInfo']).explode('lossInfo').reset_index(drop=True)
df = df.join(pd.json_normalize(df.pop('lossInfo')))
'''
|    | metaData.formName   | metaData.user   | report.from   | report.to   | locationName.name   |   locationName.locNbr | locationDetails.locNm   | locationDetails.locAddress.locCity   | locationDetails.locAddress.locStateCd   | locationDetails.state   | locationDetails.lossLocation   |
|---:|:--------------------|:----------------|:--------------|:------------|:--------------------|----------------------:|:------------------------|:-------------------------------------|:----------------------------------------|:------------------------|:-------------------------------|
|  0 | A1                  | Test User       | 12/12/2021    | 12/12/2022  | test1               |                    12 | xyz                     | abc                                  | abcd                                    | ab                      | cd                             |
|  1 | A1                  | Test User       | 12/12/2021    | 12/12/2022  | test11              |                   121 | xyz1                    | abc1                                 | abcd1                                   | ab1                     | cd1                            |
'''
Answer from Bushmaster on Stack Overflow
Top answer
1 of 2
2
row = 1

def TraverseJSONTree(jsonObject, main_title=None, count=0):
    if main_title is None:
        main_title = title = jsonObject.get('title')
    else:
        title = jsonObject.get('title')
    url = jsonObject.get('url')

    print 'Title: ' + title + ' , Position: ' + str(count)

    if main_title is not None:
        worksheet.write_string(row, 0, title)
    worksheet.write_string(row, count, title)
    worksheet.write_string(row, 6, url)
    global row
    row+=1 

    subCategories =  jsonObject.get('subCategory',[])

    for category in subCategories:
        TraverseJSONTree(category, main_title, count+1)

for jsonObject in json.loads(jsonArray):
    TraverseJSONTree(jsonObject)

it will return your expected output as it needs a check if category is there then you have to right the original title on the 0th col in excel reamin as same.

2 of 2
2

Modification : Simplest way to do this would be to use csv module, say we have the whole json in the variable a

import csv
import cPickle as pickle 

fieldnames = ['Category1', 'Category1.1', 'url']
csvfile = open("category.csv", 'wb')
csvfilewriter = csv.DictWriter(csvfile, fieldnames=fieldnames,dialect='excel', delimiter=',')
csvfilewriter.writeheader()

for b in a:     
    data = []
    data.append(b['title'])
    data.append("")
    data.append(b['url'])
    csvfilewriter.writerow(dict(zip(fieldnames,data)))
    data = []
    for i in xrange(len(b['subCategory'])):
        data.append(b['title'])
        data.append(b['subCategory'][i]['title'])
        data.append(b['subCategory'][i]['url'])
        csvfilewriter.writerow(dict(zip(fieldnames,data)))

You will have the desired csv in the same location. This works for only two subcategories (because i have checked the data given by you and say there were only two categories (ie 1 and 1.1)) but in case you want for more than repeat the same(I know it's not the most efficient way couldn't think of any in such a short time)

You can also use pandas module to convert the dictionary import pandas as pd pd.DataFrame.from_dict(dcitionaty_element)

And then do it on all the dictionaries in that json and merge them and save it to a csv file.

🌐
GitHub
github.com › oarepo › json-excel-converter
GitHub - oarepo/json-excel-converter: A python library to convert an array or stream of JSONs into CSV or Excel. Currently beta, use at your own risk
XLSX writer caches all the data before writing them to excel so the restart just means discarding the cache. If you know the size of the array in advance, you should pass it in options. Then no processing restarts are required and LinearizationError is not raised. from json_excel_converter import Converter, Options from json_excel_converter.xlsx import Writer data = [ {'a': [1]}, {'a': [1, 2, 3]} ] options = Options() options['a'].cardinality = 3 conv = Converter(options=options) writer = Writer(file='/tmp/test.xlsx') conv.convert(data, writer) # or conv.convert_streaming(data, writer) # no exception occurs here
Starred by 24 users
Forked by 10 users
Languages   Python 100.0% | Python 100.0%
🌐
YouTube
youtube.com › watch
Query APIs using Python (Part 2) - Nested JSON to Dataframe to Excel - YouTube
How to query APIs using Python and handle Nested JSON #api #apidevelopment #python #learningpython #pythoncoding #pythonprogramming #pythonforbeginners #howt...
Published   December 16, 2022
🌐
Seaborn Line Plots
marsja.se › home › programming › python › how to convert json to excel in python with pandas
How to Convert JSON to Excel in Python with Pandas
August 20, 2023 - Remember, this data is nested, and one very neat thing with the JSON to Excel converter package is that it can handle this very nicely (see the image below for the resulting Excel file).
🌐
GitHub
github.com › vinay20045 › json-to-csv
GitHub - vinay20045/json-to-csv: Nested JSON to CSV Converter · GitHub
Nested JSON to CSV Converter. This python script converts valid, preformatted JSON to CSV which can be opened in excel and other similar applications. This script can handle nested json with multiple objects and arrays.
Starred by 290 users
Forked by 213 users
Languages   Python
🌐
Like Geeks
likegeeks.com › home › python › pandas › convert json to excel using python pandas
Convert JSON to Excel using Python Pandas
Learn how to convert JSON to Excel using Pandas in Python through different examples, covering simple to nested data structures.
Top answer
1 of 2
1

Expanding to what Corralien wrote, try something like this:

import json
import pandas as pd

data = json.loads(response_json)
df = pd.concat({k: pd.json_normalize(v) for k, v in data.items()}).droplevel(1)

df = pd.concat((df, pd.concat({k: pd.json_normalize(v) for k, v in df['service.services'].items()}).droplevel(1).add_prefix('service.')), axis=1).drop(columns='service.services')

This works under the assumption you will always have a list under the service.services column.

Output:

|    |   Price |   category |   service.id | service.name   | service.description   | service.Validity   |   service.order | service.selection   |   creditTO.id |   creditTO.duration | creditTO.Type   |   creditTO.Tax |   creditTO.total | creditTO.promotion   |   service.id | service.financeable   | service.Execution   |   service.serviceId | service.label   |   service.benefit.id | service.benefit.name   | service.benefit.Priced   |
|:---|--------:|-----------:|-------------:|:---------------|:----------------------|:-------------------|----------------:|:--------------------|--------------:|--------------------:|:----------------|---------------:|-----------------:|:---------------------|-------------:|:----------------------|:--------------------|--------------------:|:----------------|---------------------:|:-----------------------|:-------------------------|
| A  |     200 |        620 |           15 | KAL            | Description           |                    |               0 | False               |             0 |                   6 | standard        |             51 |              400 | False                |          100 | True                  |                     |                 112 | Colab           |                  235 | ZSX                    |                          |
| B  |     200 |        620 |           15 | BTX            | Description           |                    |               0 | False               |             0 |                   9 | standard        |             51 |              400 | False                |          100 | True                  |                     |                 112 | Colab           |                  235 | ZSX                    |                          |
| C  |     600 |        620 |           15 | FLS            | Description           |                    |               0 | False               |             0 |                  12 | standard        |             51 |              400 | False                |          100 | True                  |                     |                 112 | Colab           |                  235 | ZSX                    |                          |
| D  |     705 |        620 |           15 | TRW            | Description           |                    |               0 | False               |             0 |                  18 | standard        |             67 |              245 | False                |          100 | True                  |                     |                 112 | Colab           |                  235 | ZSX                    |                          |
2 of 2
1

You can iterate on first level records to create individual dataframes then concatenate them to get the expected output:

import json
import pandas as pd

data = json.loads(response_json)
df = pd.concat({k: pd.json_normalize(v) for k, v in data.items()}).droplevel(1)

Output:

>>> df
   Price  category  service.id service.name service.description  ... creditTO.duration  creditTO.Type creditTO.Tax  creditTO.total  creditTO.promotion
A    200       620          15          KAL         Description  ...                 6       standard           51             400               False
B    200       620          15          BTX         Description  ...                 9       standard           51             400               False
C    600       620          15          FLS         Description  ...                12       standard           51             400               False
D    705       620          15          TRW         Description  ...                18       standard           67             245               False
Find elsewhere
🌐
The Bricks
thebricks.com › resources › guide-how-to-convert-json-to-excel-in-python-using-chatgpt
How to Convert Json to Excel in Python using ChatGPT
By writing a Python script that handles the entire conversion, you can save time and reduce the risk of human error. Here's a basic outline of what such a script might look like: import pandas as pd from pandas import json_normalize def convert_json_to_excel(json_file_path, excel_file_path): # Load JSON data data_frame = pd.read_json(json_file_path) # Flatten nested JSON flat_data_frame = json_normalize(data_frame.to_dict(orient='records')) # Save to Excel flat_data_frame.to_excel(excel_file_path, index=False) print(f"Data successfully saved to {excel_file_path}") # Example usage convert_json_to_excel('path_to_your_file.json', 'output.xlsx')
🌐
PyPI
pypi.org › project › json-excel-converter
json-excel-converter - JSON to excel convertor
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Python Forum
python-forum.io › thread-19096.html
Nested json to excel using python
Hi, I am converting nested json to excel in below format. My nested object is not populating in seperate table.Can you please help. I am using json_load. json data: Output:{ 'domain': { 'Switch': [ { 'id': '1', 'Config...
🌐
e-iceblue
e-iceblue.com › Tutorials › Python › Spire.XLS-for-Python › Program-Guide › Conversion › json-to-excel-python.html
Convert JSON to/from Excel in Python – Full Guide with Examples
You can use the json module in Python to load structured JSON data, and then use a library like Spire.XLS to export it to .xlsx. Spire.XLS allows writing headers, formatting Excel cells, and handling nested JSON via flattening.
🌐
GeeksforGeeks
geeksforgeeks.org › convert-nested-json-to-csv-in-python
Convert nested JSON to CSV in Python | GeeksforGeeks
August 23, 2021 - JSON supports multiple nests to create complex JSON files if required. Our job is to convert the JSON file to a CSV format. There can be many reasons as to why we need to perform this conversion. CSV are easy to read when opened in a spreadsheet GUI application like Google Sheets or MS Excel.
🌐
Python.org
discuss.python.org › python help
Json to excel conversion - Python Help - Discussions on Python.org
July 28, 2023 - Hi, I am trying to convert json data of Skype chats into an Excel sheet. I used a python script to convert json data into an Excel file. import pandas as pd df = pd.read_json(‘file_data.json’) df.to_excel(‘output2.xlsx’, index=False) The cells in one of the columns in the created Excel ...
🌐
Like Geeks
likegeeks.com › home › python › pandas › convert nested json to csv using python pandas
Convert Nested JSON to CSV using Python Pandas
Merge Multiple JSON files in Python using Pandas · Convert Pandas DataFrame to Nested (Hierarchical) JSON · Read JSON from API using requests and Pandas read_json · Convert JSON to Excel using Python Pandas · Convert CSV to SQL using Python Pandas · Export XML to CSV using Python Pandas ·
🌐
Horilla
horilla.com › blogs › how-to-convert-json-to-excel-using-python
How to Convert JSON to Excel Using Python | Blogs | Free HRMS | Horilla
April 29, 2025 - By using pandas with openpyxl, converting JSON to Excel becomes incredibly straightforward, whether you’re dealing with a single object, a list of entries, or even nested structures.
🌐
W3Resource
w3resource.com › JSON › snippets › convert-json-to-excel-in-python-with-examples.php
Convert JSON to Excel
By specifying df["glossary"], it extracts and normalizes the contents under the "glossary" key, creating individual columns for each nested field. ... Saves the normalized DataFrame to an Excel file without the index.
🌐
Pangaeax
community.pangaeax.com › thread › best-way-to-convert-api-json-response-to-excel-in-python
Best way to convert API JSON response to Excel in Python? | Pangaea X Community
1 month ago - In Python, this is usually done ... pd.json_normalize(data) df.to_excel("output.xlsx", index=False) pd.json_normalize() helps flatten nested JSON structures into a tabular format, which makes it easier to export to Excel....