Hello Stack社区!
我今天有问题。我需要通过API检索类似于字符串的JSON,然后从该字符串中获取一些值,然后根据这些值创建JSON文件。如果文件已经存在,则需要更新现有值。
我在某处读到,最简单的方法是每次都删除前一个文件。但是我想知道如何做到这一点,而不必每次都创建一个新文件,而是更新现有文件。
这是我现在要进行的更新过程:
#applied if the file was created once
if os.path.exists(filepath):
with open(filepath, 'r') as file:
try:
#load the existing host file
HostList = json.load(file)
#add the total of host contained in the API json
HostList['total'] += apijson['data']['total']
#get the json host dictionnaries
APIHostList = apijson['data']['entries']
#For each host in the list
for apihost in APIHostList:
#if host already exist, reduce the total
if any(d['hostname'] == apihost['hostname'] for d in HostList):
HostList['total'] -= 1
#else add the host to the json
else:
newhost = {
'hostname' : apihost['hostname'],
'ip_address' : apihost['ip_address'],
'OS' : apihost['os']['product_name'],
'id' : apihost['id'],
'timestamp' : apihost['timestamp']
}
HostList['hosts'].append(newhost)
except:
print('Error')
return
with open(filepath, 'w') as file:
json.dump(HostList, file, indent=2)
我最想拥有的是这样的东西:
#if host already exist, reduce the total
if any(d['hostname'] == apihost['hostname'] for d in HostList):
d['timestamp'] = apihost['timestamp']
d['ip_address'] = apihost['ip_address']
d['somevalue'] = apihost['someothervalue']
HostList['total'] -= 1
这不起作用,但是如果存在类似的东西,那将是完美的。我尝试使用嵌套的for循环,但是对于优化来说,这是非常糟糕的:
#For each host in the list
for apihost in APIHostList:
#For each host in the existing list
for existinghost in HostList:
if apihost['hostname'] == existinghost ['hostname']:
'''Do some updates here'''
感谢您的帮助:)