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.

Answer from d-ashu 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.

🌐
Stack Overflow
stackoverflow.com › questions › 64854786 › reading-several-nested-json-files-from-a-specific-folder-into-excel-using-pyth
Reading several nested .json files from a specific folder, into excel using python/pandas - Stack Overflow
import os import json import pandas as pd from pandas.io.json import json_normalize for js in [x for x in os.listdir() if x.endswith('.json')]: with open(js,'r') as f: data = json.loads(f.read()) multiple_level_data = pd.json_normalize(data, record_path =['data'], errors='ignore', meta =['total-count'], meta_prefix='config_params_', record_prefix='dbscan_') multiple_level_data.to_excel(js+'converted.xlsx', index=False)
🌐
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 - from json_excel_converter import Converter from json_excel_converter.xlsx import Writer url = 'https://think.cs.vt.edu/corgis/datasets/json/broadway/broadway.json' resp = requests.get(url=url) conv = Converter() conv.convert(resp.json(), Writer(file='./SimData/ExcelData.xlsx'))Code language: Python (python) This package is straightforward to use. We converted the airlines.json data to an Excel file in the example code above. 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).
🌐
Stack Overflow
stackoverflow.com › questions › 65239698 › get-data-from-json-nested-arrays-and-put-it-into-excel
python - Get data from JSON nested arrays and put it into excel - Stack Overflow
... you need json to read it and some module to write in excel (you can even write it as CSV using standard module csv) - rest you can do with for-loop` without any other module. ... I faced a similar problem during one of my internships.
🌐
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 · GitHub
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
🌐
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.
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')
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
🌐
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...
🌐
Medium
medium.com › coinmonks › parsing-a-spreadsheet-into-a-json-file-using-python-6118f5c70bd3
Parsing a Spreadsheet Into a JSON File Using Python | by Aisha Ayoub | Coinmonks | Medium
June 24, 2022 - The following article explains how to parse data from a .csv file and a .xls file into .json file using python with multiple levels of dependency. We first prepared a CSV spreadsheet with a number of redundant data we will represent in a nested json format.
🌐
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.
🌐
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. Please see the explanation below and the sample files to understand how this works.
Starred by 290 users
Forked by 213 users
Languages   Python
🌐
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 ...
🌐
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
🌐
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
This tutorial provides a complete, developer-focused guide to converting between JSON and Excel in Python. You'll learn how to handle nested data, apply Excel formatting, and resolve common conversion or encoding issues.
🌐
Stack Overflow
stackoverflow.com › questions › 75159500 › transform-data-into-excel-from-deeply-nested-json
python - Transform data into excel from deeply nested json - Stack Overflow
#f = open('file.json') data1 = json.load(open('file.json')) print("data1",data1) data = data1 ['balanceSheetHistoryQuarterly'] print("dftyp",data) data1 =pd.json_normalize(data['balanceSheetStatements']) #data1.columns = pd.MultiIndex.from_tuples(zip(['balanceSheetStatements'], data1.columns)) print("data1",data1) data1.to_excel("output\\DATAFILE4.xlsx") ... import numpy as np import pandas as pd # Turn the nested list into a dataframe df = pd.DataFrame(data1['balanceSheetHistoryQuarterly']['balanceSheetStatements']) # Extract the value of 'raw' as columns df['intangibleAssets'] = [i['raw'] for i in df['intangibleAssets']] df['capitalSurplus'] = [i['raw'] for i in df['capitalSurplus']] # Export to CSV df.to_csv('your_file_name.csv')
🌐
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 - This guide will walk you through an easy and effective way to convert JSON data into an Excel file using Python.