为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 177 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号