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])

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM