Reputation: 177
I am trying to add an element to a JSON string which is made from an element value in that string. For example my string is:
{'stock': [{'weight': '80', 'warehouse': 1}, {'weight': '40', 'warehouse': 2}, {'weight': '100', 'warehouse': 1}...]}
And I want to add a text to the 'weight' element and then save that new element as 'value'. So the result should look like this:
{'products': [{'weight': '80', 'warehouse': 1, 'value': 'weight 80 lbs'}, {'weight': '40', 'warehouse': 2, 'value': 'weight 40 lbs'}, {'weight': '100', 'warehouse': 1, 'value': 'weight 100 lbs'}...]}
And my JSON string which I want to edit has much more 'products' than this example string.
Upvotes: 1
Views: 65
Reputation: 119
A second answer if the other is confusing.
dict = {'stock': [ {'weight': '80', 'warehouse': 1}, {'weight': '40', 'warehouse': 2}, {'weight': '100', 'warehouse': 1} ]}
# loop throught keys
# loop through values of keys
# append new value to list
for key in dict:
for values in dict[key]:
values["value"] = "weight " + values["weight"]+ " lbs";
print(dict)
I would recommend learning more about dictionary manipulation.
Output
{
'stock': [
{'weight': '80', 'warehouse': 1, 'value': 'weight 80 lbs'},
{'weight': '40', 'warehouse': 2, 'value': 'weight 40 lbs'},
{'weight': '100', 'warehouse': 1, 'value': 'weight 100 lbs'}
]}
Upvotes: 0
Reputation: 11342
It looks like you can just update the list items:
dd = {'stock': [{'weight': '80', 'warehouse': 1}, {'weight': '40', 'warehouse': 2}, {'weight': '100', 'warehouse': 1}]}
for d in dd['stock']:
d['value'] = 'weight ' + d['weight'] + ' lbs'
print(dd)
Output
{'stock': [{'weight': '80', 'warehouse': 1, 'value': 'weight 80 lbs'}, {'weight': '40', 'warehouse': 2, 'value': 'weight 40 lbs'}, {'weight': '100', 'warehouse': 1, 'value': 'weight 100 lbs'}]}
Upvotes: 1