Python - 将元素添加到 json 文件

在我的 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)


慕少森
浏览 179回答 2
2回答

RISEBY

请使用 PEP8 风格指南。以下代码段将起作用导入jsondef 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)

白板的微信

要将键添加到 dict,只需将其命名:your_dict['convID'] = 'convID_value'因此,您的代码将类似于:import json# read a file, or get a stringyour_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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python