如何将元素添加到JSON字符串中,该字符串依赖于Python中该字符串的另一个元素
我试图向JSON字符串中添加一个元素,该字符串由该字符串中的元素值组成。 例如,我的字符串是:如何将元素添加到JSON字符串中,该字符串依赖于Python中该字符串的另一个元素,python,json,Python,Json,我试图向JSON字符串中添加一个元素,该字符串由该字符串中的元素值组成。 例如,我的字符串是: {'stock': [{'weight': '80', 'warehouse': 1}, {'weight': '40', 'warehouse': 2}, {'weight': '100', 'warehouse': 1}...]} 我想在“weight”元素中添加一个文本,然后将新元素另存为“value”。所以结果应该是这样的: {'products': [{'weight': '80', 'w
{'stock': [{'weight': '80', 'warehouse': 1}, {'weight': '40', 'warehouse': 2}, {'weight': '100', 'warehouse': 1}...]}
我想在“weight”元素中添加一个文本,然后将新元素另存为“value”。所以结果应该是这样的:
{'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'}...]}
我要编辑的JSON字符串的“产品”比这个示例字符串多得多。看起来您可以只更新列表项:
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)
输出
{'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'}]}
{
'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'}
]}
如果另一个答案令人困惑,请给出第二个答案
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)
我建议你多了解一些
输出
{'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'}]}
{
'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'}
]}