python更新字典下嵌套数组下嵌套字典的值

已知从外层到里层:字典-->数组-->字典的数据:

datas = {'product_info': '[{"qty":"1","name":"football","price":"20","url":"www","attribute":"","image":""}]'}

需要更新qty的值为3

(1)将键product_info的值由str转为dict

import json
product_info_value = json.loads(datas['product_info'])[0]
product_info_value的结果为:
{'qty': '1', 'price': '20', 'url': 'www', 'name': 'football', 'attribute': '', 'image': ''}

(2)更新product_info_value 字典中qty的值

product_info_value['qty'] = '3'

此时product_info_value的结果为:

{'qty': '3', 'price': '20', 'url': 'www', 'name': 'football', 'attribute': '', 'image': ''}

(3)将product_info_value由字典格式变成str,并赋值给datas['product_info'](注意不要漏了[])

datas['product_info'] = json.dumps([product_info_value])

此时键product_info对应的值为:

'[{"qty": "3", "price": "20", "url": "www", "name": "football", "attribute": "", "image": ""}]'

datas的值为: 更新成功

{'product_info': '[{"qty": "3", "price": "20", "url": "www", "name": "football", "attribute": "", "image": ""}]'}

完整代码为:

import json

datas = {'product_info': '[{"qty":"1","name":"football","price":"20","url":"www","attribute":"","image":""}]'}

product_info_value = json.loads(datas['product_info'])[0]
product_info_value['qty'] = '3'
datas['product_info'] = json.dumps([product_info_value])
原文地址:https://www.cnblogs.com/kite123/p/11995040.html