亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python - 將元素添加到 json 文件

Python - 將元素添加到 json 文件

慕少森 2022-07-26 10:24:31
在我的 python 程序中使用 json 文件。我需要從函數中修改 json 文件以添加一個空的“占位符”元素。我只想為 convID 對象中包含的鍵添加一個空元素。json 庫是否允許以更簡單的方式將元素附加到 json 文件?示例.json:{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message"}我希望發生這種情況(convID表示存儲在 convID 對象中的鍵):{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message", "*convID*": "none"}我猜我必須將 json 加載到字典對象中,進行修改并將其寫回文件......但這對我來說很困難,因為我還在學習。這是我的搖擺:def updateJSON():   jsonCache={} # type: Dict   with open(example.json) as j:      jsonCache=json.load(j)   *some code to make append element modification    with open('example.json', 'w') as k:       k.write(jsonCache)
查看完整描述

2 回答

?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

請使用 PEP8 風格指南。

以下代碼段將起作用

導入json

def update_json():    with open('example.json', 'r') as file:
        json_cache = json.load(file)
        json_cache['convID'] = None
    with open('example.json', 'w') as file:
        json.dump(json_cache, file)


查看完整回答
反對 回復 2022-07-26
?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

要將鍵添加到 dict,只需將其命名:


your_dict['convID'] = 'convID_value'

因此,您的代碼將類似于:


import json


# read a file, or get a string

your_json = '{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message"}'


your_dict = json.loads(your_json)


your_dict['convID'] = 'convID_value'

因此,將它與您的代碼一起使用,它將是:


def update_json():

    json_cache = {}


    with open('example.json', 'r') as j:

        json_cache = json.load(j)


    json_cache['convID'] = 'the value you want'


    with open('example.json', 'w') as k:

        json.dump(json_cache, f)


查看完整回答
反對 回復 2022-07-26
  • 2 回答
  • 0 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號