我正在测试一个密钥,如果它存在,我正在做一个json.dump,如果不存在,我正在添加它。我还要检查另外两个键,如果它们不存在,则添加它们。我嵌套了那些二次测试。
使用此代码,如果密钥存在,它可以正常工作,但如果没有,当它添加它时,它还会在不应该添加时添加json.dump。这应该是两个不同的功能吗?或者我如何重新排列它以便在添加密钥后停止?
import json
def extract_metadata(input_filename, output_filename, wanted_key):
with open(input_filename, "r") as infile:
data = json.load(infile)
with open(output_filename, "w") as outfile:
if "extended" in data['metadata']:
if "key_1" not in data['metadata']['extended']:
data['metadata']['extended'].update(key_1={})
else:
pass
if "key_2" not in data['metadata']['extended']:
data['metadata']['extended'].update(key_2={})
else:
pass
json.dump(data["metadata"], outfile)
else:
data['metadata'].update(extended={"loadedBy": "company"})
json.dump(data['metadata'], outfile)
*******改进了工作代码********
if "extended" in data['metadata']:
if "key_1" not in data['metadata']['extended']:
data['metadata']['extended'].update(key_1={})
if "key_2" not in data['metadata']['extended']:
data['metadata']['extended'].update(key_2={})
with open(output_filename, "w") as outfile:
json.dump(data['metadata'], outfile)
else:
data['metadata'].update(extended={"loadedBy": "company"})
changed = True
if changed == True:
with open(output_filename, "w") as outfile:
json.dump(data['metadata'], outfile)
答案 0 :(得分:2)
设置一个变量,指示您是否对数据进行了任何更改。如果变量不为真,则不要转储到输出文件。
def extract_metadata(input_filename, output_filename, wanted_key):
with open(input_filename, "r") as infile:
data = json.load(infile)
changed = False
if "extended" in data['metadata']:
if "key_1" not in data['metadata']['extended']:
data['metadata']['extended'].update(key_1={})
changed = True
if "key_2" not in data['metadata']['extended']:
data['metadata']['extended'].update(key_2={})
changed = True
else:
data['metadata'].update(extended={"loadedBy": "company"})
changed = True
if changed:
with open(output_filename, "w") as outfile:
json.dump(data['metadata'], outfile)
顺便说一下,你不需要else: pass
,你可以简单地省略else:
条款。