Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON - Generating a json in a loop in python

Tags:

python

json

I have some difficulties generating a specific JSON object in python.

I need it to be in this format:

[
   {"id":0 , "attributeName_1":"value" , "attributeName_2":"value" , .... },
   {"id":1 , "attributeName_2":"value" , "attributeName_3":"value" , .... },
   .
   .
   .
]

In python, im getting the ids, attributeNames and values from 2 objects. Im trying to generate the json like this:

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

but I got this result which is not exactly what I need:

[
   {"id":0} , {"attributeName_1":"value"} , {"attributeName_2":"value"} ,
   {"id":1} , {"attributeName_2":"value"} , {"attributeName_3":"value"} , .... },
   .
   .
   .
]
like image 344
Below the Radar Avatar asked Sep 07 '13 13:09

Below the Radar


People also ask

Can you loop through JSON in Python?

Use json. loads() With the Help of the for Loop to Iterate Through a JSON Object in Python. A built-in package, json , is provided by Python, which can be imported to work with JSON form data. In Python, JSON exists as a string or stored in a JSON object.

How do you iterate over a JSON Object in Python?

Use json. loads() and a for-loop to iterate through a JSON string. Call json. loads(str) to parse a JSON string str to a Python dictionary.

How create JSON Object in for loop?

To create JSON with JavaScript for loop, we can use a for-of loop. to loop through the object entries in the sels array with a for-of loop. In it, we get the entry being looped through with sel . We add the sel.id property into json and then assign sel.

Can you loop through JSON?

To loop through a JSON array with JavaScript, we can use a for of loop. to loop through the json array with a for of loop. We assign the entry being looped through to obj . Then we get the value of the id property of the object in the loop and log it.


1 Answers

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)
like image 174
alecxe Avatar answered Oct 19 '22 14:10

alecxe