在我的python程序中使用json文件。我需要从函数中修改json文件,以添加一个空的“占位符”元素。我只想为convID对象中包含的键添加一个空元素。 json库是否允许以更简单的方式将元素添加到json文件?
example.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)
答案 0 :(得分:2)
请使用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)
答案 1 :(得分:1)
要将键添加到字典中,只需将其命名为:
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)