You could nest the dictionaries as follows:

jsondata = {}
agent={}
content={}
agent['agentid'] = 'john'
content['eventType'] = 'view'
content['othervar'] = "new"

jsondata['agent'] = agent
jsondata['content'] = content
print(json.dumps(jsondata))

Output:

print {"content": {"eventType": "view", "othervar": "new"}, "agent": {"agentid": "john"}}

Answer from C. Fennell on Stack Overflow
🌐
Esri Community
community.esri.com › t5 › python-questions › python-to-generate-dynamic-nested-json-string › td-p › 257817
Solved: Python to Generate Dynamic Nested JSON String - Esri Community
December 11, 2021 - Greetings, Using python and ArcPy search cursors, I've extracted list(s) of dictionaries containing normalized key value pairs originating from specific tables but residing in a denormalized database layer. In the same script, I am now creating a JSON string with an object containing field & value pair arrays [] that that are to contain the keys and values (key value pairs) I've already distilled into lists of dictionary structures.
Discussions

Creating nested Json structure with multiple key values in Python from Json - Stack Overflow
0 How to re-structure the below JSON data which is a result set of SQL query using cursors in python More on stackoverflow.com
🌐 stackoverflow.com
Use python to create a nested json - Stack Overflow
Since SO is not a code-writing-service, I'll give you some entry points: To handle json, take a look at json module and Python's default dicts More on stackoverflow.com
🌐 stackoverflow.com
June 25, 2015
How to Make Nested JSON Object with Python - Stack Overflow
I've done something similar with the code below but I can't figure out how I need to nest number under items. #!/usr/bin/python import json myjson = {'items':[]} d = {} d['value'] = 23 d['label'] = "test" myjson.get('items').append(d) output = json.dumps(myjson) print output More on stackoverflow.com
🌐 stackoverflow.com
May 8, 2017
Build a double nested JSON object
In your wanted output, content is a list so just declare it as such then append whatever data you want to it. import json json_data = {} json_data["content"] = [] content = {} content["eventType"] = "view" content["othervar"] = "new" json_data["content"].append(content) print(json.dumps(json_data, indent=4)) # Output { "content": [{ "eventType": "view", "othervar": "new" }] } More on reddit.com
🌐 r/learnpython
3
1
January 23, 2024
Top answer
1 of 2
9

What @andrea-f looks good to me, here another solution:

Feel free to pick in both :)

import json

dic = {
        "bomber": [1, 2, 3, 4, 5],
        "irritation": [1, 3, 5, 7, 8]
      }

filename = "abc.pdf"

json_dict = {}
data = []

for k, v in dic.iteritems():
  tmp_dict = {}
  tmp_dict["keyword"] = k
  tmp_dict["term_freq"] = len(v)
  tmp_dict["lists"] = [{"occurrance": i} for i in v]
  data.append(tmp_dict)

json_dict["filename"] = filename
json_dict["data"] = data

with open("abc.json", "w") as outfile:
    json.dump(json_dict, outfile, indent=4, sort_keys=True)

It's the same idea, I first create a big json_dict to be saved directly in json. I use the with statement to save the json avoiding the catch of exception

Also, you should have a look to the doc of json.dumps() if you need future improve in your json output.

EDIT

And just for fun, if you don't like tmp var, you can do all the data for loop in a one-liner :)

json_dict["data"] = [{"keyword": k, "term_freq": len(v), "lists": [{"occurrance": i} for i in v]} for k, v in dic.iteritems()]

It could gave for final solution something not totally readable like this:

import json

json_dict = {
              "filename": "abc.pdf",
              "data": [{
                        "keyword": k,
                        "term_freq": len(v),
                        "lists": [{"occurrance": i} for i in v]
                       } for k, v in dic.iteritems()]
            }

with open("abc.json", "w") as outfile:
    json.dump(json_dict, outfile, indent=4, sort_keys=True)

EDIT 2

It looks like you don't want to save your json as the desired output, but be abble to read it.

In fact, you can also use json.dumps() in order to print your json.

with open('abc.json', 'r') as handle:
    new_json_dict = json.load(handle)
    print json.dumps(json_dict, indent=4, sort_keys=True)

There is still one problem here though, "filename": is printed at the end of the list because the d of data comes before the f.

To force the order, you will have to use an OrderedDict in the generation of the dict. Be careful the syntax is ugly (imo) with python 2.X

Here is the new complete solution ;)

import json
from collections import OrderedDict

dic = {
        'bomber': [1, 2, 3, 4, 5],
        'irritation': [1, 3, 5, 7, 8]
      }

json_dict = OrderedDict([
              ('filename', 'abc.pdf'),
              ('data', [ OrderedDict([
                                        ('keyword', k),
                                        ('term_freq', len(v)),
                                        ('lists', [{'occurrance': i} for i in v])
                                     ]) for k, v in dic.iteritems()])
            ])

with open('abc.json', 'w') as outfile:
    json.dump(json_dict, outfile)


# Now to read the orderer json file

with open('abc.json', 'r') as handle:
    new_json_dict = json.load(handle, object_pairs_hook=OrderedDict)
    print json.dumps(json_dict, indent=4)

Will output:

{
    "filename": "abc.pdf", 
    "data": [
        {
            "keyword": "bomber", 
            "term_freq": 5, 
            "lists": [
                {
                    "occurrance": 1
                }, 
                {
                    "occurrance": 2
                }, 
                {
                    "occurrance": 3
                }, 
                {
                    "occurrance": 4
                }, 
                {
                    "occurrance": 5
                }
            ]
        }, 
        {
            "keyword": "irritation", 
            "term_freq": 5, 
            "lists": [
                {
                    "occurrance": 1
                }, 
                {
                    "occurrance": 3
                }, 
                {
                    "occurrance": 5
                }, 
                {
                    "occurrance": 7
                }, 
                {
                    "occurrance": 8
                }
            ]
        }
    ]
}

But be carefull, most of the time, it is better to save a regular .json file in order to be cross languages.

2 of 2
3

Your current code is not working because the loop iterates through the before-last item adding the }, then when the loop runs again it sets the flag to false, but the last time it ran it added a , since it thought that there will be another element.

If this is your dict: a = {"bomber":[1,2,3,4,5]} then you can do:

import json
file_name = "a_file.json"
file_name_input = "abc.pdf"
new_output = {}
new_output["filename"] = file_name_input

new_data = []
i = 0
for key, val in a.iteritems():
   new_data.append({"keyword":key, "lists":[], "term_freq":len(val)})
   for p in val:
       new_data[i]["lists"].append({"occurrance":p})
   i += 1

new_output['data'] = new_data

Then save the data by:

f = open(file_name, 'w+')
f.write(json.dumps(new_output, indent=4, sort_keys=True, default=unicode))
f.close()
🌐
Stack Overflow
stackoverflow.com › questions › 31050799 › use-python-to-create-a-nested-json
Use python to create a nested json - Stack Overflow
June 25, 2015 - import json final = [] count = 0 postID = 224 while postID < 1200: final.append({count: {"posted_ID":postID}}) count = count + 1 postID = postID * 2 print str(json.dumps(final))
🌐
DEV Community
dev.to › mandrewcito › nested-json-to-python-object--5ajp
Nested json to python object - DEV Community
January 29, 2019 - The follwing code creates dynamic attributes with the objects keys recursively. ... import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("cfg.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if type(value) is list: return [self.compute_attr_value(x) for x in value] elif type(value) is dict: return AppConfiguration(value) else: return value
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › build a double nested json object
r/learnpython on Reddit: Build a double nested JSON object
January 23, 2024 -

This is what I want to generate to match a required file format (notice the extra level of brackets):

{
    "content": [{
        "eventType": "view",
        "othervar": "new"
    }]
}

sample code:

import json

jsondata = {}
content={}
content['eventType'] = 'view'
content['othervar'] = "new"

jsondata['content'] = content
print(json.dumps(jsondata, indent=4))

Current output:

{
    "content": {
        "eventType": "view",
        "othervar": "new"
    }
}  

EDIT: Thanks so much. I come from a long R background and am still learning the Python details.

🌐
Reddit
reddit.com › r/learnpython › help with using python dictionaries to create multi level nested json data
r/learnpython on Reddit: Help with using Python dictionaries to create multi level nested JSON data
October 17, 2016 -

I am a Python n00b and perhaps there is a better way to accomplish what I am trying to do but my goal is to create a multi level JSON schema and populate data dynamically via Python dictionaries.

EDIT: Added my attempted Python dictionary usage which doesn't allow me to populate data in the service_components node. The goal is to understand how to structure a Python dictionary that can be converted to the example JSON format below.

ambari_services = {'service_name':[],'service_components':[{'component_name':[],'service_name':[]}]}

ambari_services['service_name'].append('YARN')
ambari_services['service_components']['component_name']

I am using the Python requests module and json module with the Hadoop Ambari REST API to pull out data for services and service components. I have manually created the below example of the JSON schema I am hoping to create and dynamically populate with data via Python.

Any help and guidance would be greatly appreciated. Thanks for reading!

{
    "ambari_services": [
        {
            "service_name": "AMBARI_METRICS",
            "service_components" : [
                {
                    "component_name" : "METRICS_COLLECTOR",
                    "service_name" : "AMBARI_METRICS"
                },
                {
                    "component_name" : "METRICS_MONITOR",
                    "service_name" : "AMBARI_METRICS"
                }
            ]
        },
        {
            "service_name": "YARN",
            "service_components" : [
                {
                    "component_name" : "APP_TIMELINE_SERVER",
                    "service_name" : "YARN"
                },
                {
                    "component_name" : "NODEMANAGER",
                    "service_name" : "YARN"
                },
                {
                    "component_name" : "RESOURCEMANAGER",
                    "service_name" : "YARN"
                },
                {
                    "component_name" : "YARN_CLIENT",
                    "service_name" : "YARN"
                }
            ]
        }
    ]
}
Top answer
1 of 1
12

The csv module will handle the CSV reading nicely - including handling line breaks that are within quotes.

import csv
with open('my_csv.csv') as csv_file:
   for row in csv.reader(csv_file):
       # do work

The csv.reader object is an iterator - you can iterate through the rows in the CSV by using a for loop. Each row is a list, so you can get each field as row[0], row[1], etc. Be aware that this will load the first row (which just contains field names in your case).

As we have field names given to us in the first row, we can use csv.DictReader so that fields in each row can be accessed as row['id'], row['name'], etc. This will also skip the first row for us:

import csv
with open('my_csv.csv') as csv_file:
   for row in csv.DictReader(csv_file):
       # do work

For the JSON export, use the json module. json.dumps() will take Python data structures such as lists and dictionaries and return the appropriate JSON string:

import json
my_data = {'id': 123, 'name': 'Test User', 'emails': ['[email protected]', '[email protected]']}
my_data_json = json.dumps(my_data)

If you want to generate JSON output exactly as you posted, you'd do something like:

output = {'persons': []}
with open('my_csv.csv') as csv_file:
    for person in csv.DictReader(csv_file):
        output['persons'].append({
            'type': 'config.profile',
            'id': person['id'],
            # ...add other fields (email etc) here...
        })

        # ...do similar for config.pictures, config.status, etc...

output_json = json.dumps(output)

output_json will contain the JSON output that you want.

However, I'd suggest you carefully consider the structure of the JSON output that you're after - at the moment, you're defining an outer dictionary that serves no purpose, and you're adding all your 'config' data directly under 'persons' - you may want to reconsider this.

🌐
Hackers and Slackers
hackersandslackers.com › extract-data-from-complex-json-python
Extract Nested Data From Complex JSON
December 22, 2022 - It's a great full-featured API, but as you might imagine the resulting JSON for calculating commute time between where you stand and every location in the conceivable universe makes an awfully complex JSON structure. We're going to use the Google Maps API to get the distance between two locations, as well as the estimated duration to complete the trip. Below we see how such a request would be made via Python's requests library.
🌐
GitHub
github.com › topics › nested-json
nested-json · GitHub Topics · GitHub
A lightweight query engine that treats a folder of CSV/JSON files as a relational database. Write queries in a compact GraphQL-like syntax and get back nested JSON — no SQL, no database server. python cli json csv etl data-analysis data-processing query-language no-sql nested-json polars data-query file-query nestql graphql-like
🌐
Medium
medium.com › javarevisited › python-pandas-dataframe-to-nested-json-e53822c6dd4e
Python Pandas Dataframe to Nested JSON | by Vinesh | Javarevisited | Medium
July 22, 2022 - Python Pandas Dataframe to Nested JSON How to get desired nested JSON from python dataframe with desired JSON key names What Is Pandas In Python? Pandas is a Python package providing fast, flexible …
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-to-generate-dynamic-nested-json-string
Python To Generate Dynamic Nested Json String - GeeksforGeeks
July 23, 2025 - In this example, The code defines a Python dictionary `data_dict` representing nested data with attributes like name, age, address, and contacts. It then uses the `json.
🌐
Medium
medium.com › @mayurkoshti12 › how-to-work-with-nested-json-data-in-python-bbf51f5231c7
How to Work with Nested JSON Data in Python | Medium
October 3, 2024 - JSON is a lightweight data interchange format that’s easy for humans to read and write and easy for machines to parse and generate. It represents data as key-value pairs and supports various data types, including objects (dictionaries in Python), arrays (lists in Python), strings, numbers, booleans, and null. Nested JSON refers to JSON data structures that contain other JSON objects or arrays within them.
🌐
TecAdmin
tecadmin.net › using-nested-json-data-in-python
Working with Nested JSON Data in Python – TecAdmin
April 26, 2025 - A nested JSON object is a JSON object that contains other JSON objects or arrays as its values. This hierarchical structure allows it to represent complex data models, like a user with multiple addresses, each address containing its own set of properties. Consider a JSON file named users.json that contains data for two users, each with their own set of addresses and preferences: