JSON - Generating json in a loop in python

I have some difficulties creating 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 gets identifiers, attributes and values ​​from two objects. I am trying to create json as follows:

  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 quite what I need:

 [ {"id":0} , {"attributeName_1":"value"} , {"attributeName_2":"value"} , {"id":1} , {"attributeName_2":"value"} , {"attributeName_3":"value"} , .... }, . . . ] 
+7
json python
source share
1 answer

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

Instead, you need to define the dictionary inside the loop, fill it with the id tag and attributes, and only then add:

 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) 
+14
source share

All Articles