从JSON文件-Python中选择特定字段
我试图比较两个json文件。一个是json.dump,另一个是进入方法的新json对象 我们使用服务器的测试结果生成一个JSON文件,然后将其传递到该方法:从JSON文件-Python中选择特定字段,python,json,Python,Json,我试图比较两个json文件。一个是json.dump,另一个是进入方法的新json对象 我们使用服务器的测试结果生成一个JSON文件,然后将其传递到该方法: def save_json_results(data): if not os.listdir('/opt/Code/JSON'): with open('/opt/Code/JSON/current_json.json','w') as outfile: json.dump(data,outfile)
def save_json_results(data):
if not os.listdir('/opt/Code/JSON'):
with open('/opt/Code/JSON/current_json.json','w') as outfile:
json.dump(data,outfile)
send_json_results(data)
else:
f = open('/opt/Code/JSON/current_json.json')
file_data = json.loads(f)
d = json.loads(data)
if sorted(file_data.items()) == sorted(d.items()) and file_data.get("timestamp",{}) != d.get("timestamp",{}):
with open('/opt/Code/JSON/current_json.json','w') as outfile:
json.dump(data,outfile)
else:
os.rename('/opt/Code/JSON/current_json.json','/opt/cfm_health_checks/Code/JSON/prev_json.json')
with open('/opt/Code/JSON/current_json.json','w') as outfile:
json.dump(data,outfile)
send_json_results(data)
此方法的前提是获取正在传递的JSON对象(数据),然后检查目录是否为空,然后将此文件存储为最新的JSON,否则它将尝试打开已经存在的文件(我可能错误地认为我必须将其作为JSON对象重新加载),然后尝试比较这些文件,如果它们相同且只是时间戳不同,则不要将JSON发送到数据库(因为这只是浪费网络资源,因为没有关于测试结果的信息不同),但是它仍会使新数据=最新的JSON,否则它会将其发送到数据库并相应地重命名文件
{
"acronym": "",
"api": [],
"cell_version": "",
"cfm": [],
"city": "Belfast",
"country": "UK",
"latitude": 54.614443,
"longitude": -5.899953,
"nas": [],
"node": [],
"number_of_cells": "",
"switch": [],
"timestamp": "2015-01-19 15:04:13.489097"
}
上面的JSON示例。由
JSON.loads返回的d
和file\u数据
对象应具有标准的python字典接口
因此,您应该能够使用d[“acronym”]
访问d
中的首字母缩写值
您还可以对文件_data.items()中的keyvaluepair执行:
以迭代每个JSON条目,并根据密钥名称对每个键值对应用单独的比较
你也可以这样做
如果k[0]!=“时间戳”]=“文件数据[k[0]]如果k[0]!=“时间戳”]=“文件数据[k[0]]如果k[0]!=“时间戳”]
尽管这是一条很长的线,我个人不会让代码审查通过。非常感谢您的帮助!用d[首字母缩略词]的方法!