已知從外層到里層:字典-->數組-->字典的數據:
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])