1. 将 JSON 文件读为字典
def read_json(file_path):
with open(file_path, 'r') as f:
content = f.readline()
if content:
content = json.loads(content)
else:
content = {}
return content
2. 将键值对写入 JSON 文件
def to_json(key, value, file_path):
content = read_json(file_path)
if value not in content.values():
content[key] = value
content = json.dumps(content)
with open(file_path, 'w') as f:
f.write(content)