I'm creating a function (processElements) that uses a JSON object as variable (json_template).
This function is in charge of generating an array of that JSON object (jsonElementArray), setting up the values according to what is received as function parameter (fruitsArray).
The problem is that when I'm calling the function, it's overwriting the parameter of the elements that make up the array. The parameter of all elements take the value of the parameter of the last element.
The mentioned function is the as follows:
def processElements(fruitsArray):
jsonElementArray = []
for fruit in fruitsArray:
jsonElement = json_template
jsonElement['name'] = fruit['id']
jsonElementArray.append(jsonElement)
return jsonElementArray
The JSON template that I use as variable in the function is as follows:
json_template = {
"type": "fruit",
"name": ""
}
A sample JSON with the array that the function could receive as input is as follows:
jsonSample = {
"fruits": [
{
"id": "apple"
},
{
"id": "banana"
},
{
"id": "orange"
}
]
}
The function is being used as follows:
def prueba(request):
print(processElements(jsonSample["fruits"]))
The (not wanted) result is as follows:
{'type': 'fruit', 'name': 'orange'}{'type': 'fruit', 'name': 'orange'}{'type': 'fruit', 'name': 'orange'}
The expected result is as follows:
{'type': 'fruit', 'name': 'apple'}{'type': 'fruit', 'name': 'banana'}{'type': 'fruit', 'name': 'orange'}