The problem is that you are appending to data multiple times in the loop: first {"id":feature.pk}, then {attribute.attribute.name : attribute.value} in the inner loop.

Instead, you need to define a dictionary inside the loop, fill it with id item and attributes and only then append:

data=[]
for feature in features_selected:
    item = {"id": feature.pk}
    for attribute in attributes_selected:
        if attribute.feature == feature:
            item[attribute.attribute.name] = attribute.value
    data.append(item)

jsonData=json.dumps(data)
Answer from alecxe on Stack Overflow
Top answer
1 of 2
30

The problem is that you are appending to data multiple times in the loop: first {"id":feature.pk}, then {attribute.attribute.name : attribute.value} in the inner loop.

Instead, you need to define a dictionary inside the loop, fill it with id item and attributes and only then append:

data=[]
for feature in features_selected:
    item = {"id": feature.pk}
    for attribute in attributes_selected:
        if attribute.feature == feature:
            item[attribute.attribute.name] = attribute.value
    data.append(item)

jsonData=json.dumps(data)
2 of 2
1

For those who came here looking for a way to create an arbitrary json in a loop, the question is akin to creating a Python list / dictionary in a loop because the canonical way to build a json in Python is to build the corresponding Python data structure (list -> json array, dictionary -> json object) and serialize it using json.dump (to store it in a json file) or json.dumps (to create a json string in memory).

The case in the OP may be one case where a comprehension makes the loop more intuitive and less error-prone. The nested structure in the OP can be written as a dict comprehension nested inside a list comprehension. The idea is to build a dictionary in each outer iteration using an inner iteration. Two dictionaries can be merged as well, which is put to use since an 'id' key is needed in each dict. A similar example is as follows:

data = [{'id': i+10, **{j: j // 2 for j in range(i, i+60) if j % 30 == 0}} for i in range(2)]

# convert to a json string
json_string = json.dumps(data)
# '[{"id": 10, "0": 0, "30": 15}, {"id": 11, "30": 15, "60": 30}]'

# or
# write to a json file
with open('myjson.json', 'w') as f:
    json.dump(data, f)
Discussions

How to create JSON data in a loop in Python? - Stack Overflow
I can access it directly but I need to create a loop so I can add multiple inserts into database. ... It looks like for prod in dmp: does that - iterates over a list. More on stackoverflow.com
🌐 stackoverflow.com
Using Python to loop through JSON dictionary that re-uses the same key?
To clarify, you're looking at the $ key right? - If this is the case, it looks like you can differentiate with the accompanying @id key. They seem to be consistent between the attribute structures e.g. it looks like the @id value 0x12d7f will consistently contain an IP in the paired $ key value . More on reddit.com
🌐 r/learnpython
5
3
October 13, 2022
Create JSON in for loop in Python - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
January 24, 2020
python - Create multiple json objects by using for loop - Stack Overflow
I'm in the process of creating a billing system and need to output some data from my API. I want to return the data as JSON, but i'm only getting one of the db entries in my output, even though the... More on stackoverflow.com
🌐 stackoverflow.com
May 10, 2020
🌐
Stack Overflow
stackoverflow.com › questions › 50011439 › python-for-loop-through-array-creating-json-file
Python for loop through array creating JSON file - Stack Overflow
# Creates a storage file for the with open('placeInfo.json', 'w') as outfile: json.dump(api.trends_place(id=location_array[1]), outfile) with open('placeInfo.json', 'r') as handle: parsed = json.load(handle) prettyFile = json.dumps(parsed, indent=4, sort_keys=True) pfFile = json.loads(prettyFile) #use for indexing print prettyFile x = 'number1' f = open(x + 'newFile.json', 'w') f.write(prettyFile) What I want to do is loop through an array (0-17 elements) and use id=location_array[x] to index each location within the array.
🌐
Stack Overflow
stackoverflow.com › questions › 50750861 › how-to-create-json-data-in-a-loop-in-python
How to create JSON data in a loop in Python? - Stack Overflow
Is this how you turn dict into list ? for prod, value in data.items(): productId = prod['productId'] ... prod = list(prod) will do that, but I think you're misunderstanding the problem you're having - that' s almost definitely not what you want it to do. Try just accessing prod['productId'] instead of looping.
🌐
Reddit
reddit.com › r/learnpython › using python to loop through json dictionary that re-uses the same key?
r/learnpython on Reddit: Using Python to loop through JSON dictionary that re-uses the same key?
October 13, 2022 -

I'm trying to restructure JSON output from a API to the specific format that Ansible wants for it's invetory file. To do this I thought I would loop through the JSON and grab the variables I need and then feed that into the proper structure. However, I noticed my API JSON is using the same $ key for multiple variables. How can I properly reference and differentiate between the variables? Here is an example:

 "model-responses": {
        "model": [
            {
                "@mh": "0x11e013",
                "attribute": [
                    {
                        "@id": "0x1006e",
                        "$": "switch1"
                    },
                    {
                        "@id": "0x23000e",
                        "$": "Raritan Computer, Inc.DV"
                    },
                    {
                        "@id": "0x12d7f",
                        "$": "10.10.10.1"
                    },
                    {
                        "@id": "0x10052",
                        "$": "PX2 030610"
                    }
                ]
            },
            {
                "@mh": "0x115014",
                "attribute": [
                    {
                        "@id": "0x1006e",
                        "$": "switch2"
                    },
                    {
                        "@id": "0x23000e",
                        "$": "DCS-7010T-48"
                    },
                    {
                        "@id": "0x12d7f",
                        "$": "10.10.10.2"
                    },
                    {
                        "@id": "0x10052",
                        "$": "Arista Networks EOS version 4.22.3M-INT running on an Arista Networks DCS-7010T-48"
                    }
                ]
            },
🌐
Quora
quora.com › How-do-I-loop-through-a-JSON-file-with-multiple-keys-sub-keys-in-Python
How to loop through a JSON file with multiple keys/sub-keys in Python - Quora
Answer (1 of 4): You have to do it recursively. Here is an example. [code]a_dict = {'a': 'a value', 'b': {'b.1': 'b.1 value'}} def iterate(dictionary): for key, value in dictionary.items(): if isinstance(value, dict): iterate(value) continue print('key {...
🌐
Python Forum
python-forum.io › thread-39669.html
Loop through json file and reset values [SOLVED]
March 23, 2023 - Hello everybody, I have a json file which stores information for different people, which looks like this: { "person": }Everytime my script get's executed I want to select a random person. Once the per
Find elsewhere
🌐
CopyProgramming
copyprogramming.com › howto › json-generating-a-json-in-a-loop-in-python
Looping Through JSON Objects and Generating JSON in Loops: Complete Guide for Python and JavaScript in 2026 - Javascript python loop in a json by object
December 20, 2025 - This comprehensive guide covers the most practical and performant approaches for both languages, along with the latest best practices and tools for 2026. Python transforms JSON strings into dictionaries using json.loads(), then iterates through them with standard Python loops and methods.
🌐
Quora
quora.com › How-can-I-use-a-loop-inside-a-JSON-object-for-inserting-a-new-object-inside-that-main-single-object
How to use a loop inside a JSON object for inserting a new object inside that main single object - Quora
Answer (1 of 3): As far as I know, and according to this grammar, JSON there is no loop construct in Json. So, you need to do that in the programming language in which the json api of your choice is implemented.
🌐
Stack Overflow
stackoverflow.com › questions › 59895056 › create-json-in-for-loop-in-python
Create JSON in for loop in Python - Stack Overflow
January 24, 2020 - # Clear screen each time when run script from clear_screen import clear clear() # Import libs import investpy import json # Array for all countries and their bonds json_data = {} # Loop over all countries for country_name in investpy.bonds.get_bond_countries(): # Create 'array' where we can store all bonds for that country bonds_tmp = [] # Loop over all bonds for bond_name in investpy.bonds.get_bonds_list(country_name): # And add them into tmp array bonds_tmp.append(investpy.bonds.get_bond_information(bond_name, as_json=True)) # Create 'country' item, that will contain array of all bonds above json_data[country_name.title()] = bonds_tmp # Break on first item ...
🌐
Stack Overflow
stackoverflow.com › questions › 61701327 › create-multiple-json-objects-by-using-for-loop
python - Create multiple json objects by using for loop - Stack Overflow
May 10, 2020 - 3 Writing Json in for loop in Python · 0 Create JSON object with variables from an array · 0 Creating A Dynamic nested Json Using For Loops - Python · 3 How to create multiple records (aka objects) in a JSON using a for loop · 0 iterating over json and construction python object ·
Top answer
1 of 2
2

I suggest several possible solutions.

One solution is to write custom code to slurp in the input file. I would suggest putting a special line before each JSON object in the file, such as: ###

Then you could write code like this:

import json

def json_get_objects(f):
    temp = ''
    line = next(f)  # pull first line
    assert line == SPECIAL_LINE

    for line in f:
        if line != SPECIAL_LINE:
            temp += line
        else:
            # found special marker, temp now contains a complete JSON object
            j = json.loads(temp)
            yield j
            temp = ''
    # after loop done, yield up last JSON object
    if temp:
        j = json.loads(temp)
        yield j

with open("specs_data.txt", "r") as f:
    for j in json_get_objects(f):
        pass # do something with JSON object j

Two notes on this. First, I am simply appending to a string over and over; this used to be a very slow way to do this in Python, so if you are using a very old version of Python, don't do it this way unless your JSON objects are very small. Second, I wrote code to split the input and yield up JSON objects one at a time, but you could also use a guaranteed-unique string, slurp in all the data with a single call to f.read() and then split on your guaranteed-unique string using the str.split() method function.

Another solution would be to write the whole file as a valid JSON list of valid JSON objects. Write the file like this:

{"mylist":[
# first JSON object, followed by a comma
# second JSON object, followed by a comma
# third JSON object
]}

This would require your file appending code to open the file with writing permission, and seek to the last ] in the file before writing a comma plus newline, then the new JSON object on the end, and then finally writing ]} to close out the file. If you do it this way, you can use json.loads() to slurp the whole thing in and have a list of JSON objects.

Finally, I suggest that maybe you should just use a database. Use SQLite or something and just throw the JSON strings in to a table. If you choose this, I suggest using an ORM to make your life simple, rather than writing SQL commands by hand.

Personally, I favor the first suggestion: write in a special line like ###, then have custom code to split the input on those marks and then get the JSON objects.

EDIT: Okay, the first suggestion was sort of assuming that the JSON was formatted for human readability, with a bunch of short lines:

{
    "foo": 0,
    "bar": 1,
    "baz": 2
}

But it's all run together as one big long line:

{"foo":0,"bar":1,"baz":2}

Here are three ways to fix this.

0) write a newline before the ### and after it, like so:

###
{"foo":0,"bar":1,"baz":2}
###
{"foo":0,"bar":1,"baz":2}

Then each input line will alternately be ### or a complete JSON object.

1) As long as SPECIAL_LINE is completely unique (never appears inside a string in the JSON) you can do this:

with open("specs_data.txt", "r") as f:
    temp = f.read()  # read entire file contents
    lst = temp.split(SPECIAL_LINE)
    json_objects = [json.loads(x) for x in lst]
    for j in json_objects:
        pass # do something with JSON object j

The .split() method function can split up the temp string into JSON objects for you.

2) If you are certain that each JSON object will never have a newline character inside it, you could simply write JSON objects to the file, one after another, putting a newline after each; then assume that each line is a JSON object:

import json

def json_get_objects(f):
    for line in f:
        if line.strip():
            yield json.loads(line)

with open("specs_data.txt", "r") as f:
    for j in json_get_objects(f):
        pass # do something with JSON object j

I like the simplicity of option (2), but I like the reliability of option (0). If a newline ever got written in as part of a JSON object, option (0) would still work, but option (2) would error.

Again, you can also simply use an actual database (SQLite) with an ORM and let the database worry about the details.

Good luck.

2 of 2
2

Append json data to a dict on every loop.

In the end dump this dict as a json and write it to a file.

For getting you an idea for appending data to dict:

>>> d1 = {'suku':12}
>>> t1 = {'suku1':212}
>>> d1.update(t1)
>>> d1
{'suku1': 212, 'suku': 12}
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
You can convert Python objects of the following types, into JSON strings:
🌐
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 p...
🌐
Tech-otaku
tech-otaku.com › mac › using-python-to-loop-through-json-encoded-data
Using Python to Loop Through JSON-Encoded Data – Tech Otaku
Each object representing a single macOS version contains information on that version in the form of five name/value pairs: family, version, codename, announced and released. All values are strings. To allow Python to access the JSON-encoded data we first need to open the file and then read its contents into memory.
🌐
CodeSpeedy
codespeedy.com › home › loop through a json array in python
Loop through a JSON array in Python - CodeSpeedy
September 21, 2023 - import json with open('sample_json.json', 'r') as json_file: myJSON_array = json.load(json_file) for data in myJSON_array: print("language:", data["language"]) print("duration:", data["duration"]) print("author:", data["author"]) print("site:", ...