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"} , .... },
.
.
.
]
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With