我有两个json文件,其内容如下:
文件1:
{
"name": "SES_ENABLED",
"value": "true"
},
{
"name":"SES_ADDRESS",
"value":"email-xxxxxx.aws.com"
},
{
"name":"SES_FROM_EMAIL",
"value":"abc@gmail.com"
},
{
"name":"SES_TO_EMAIL",
"value":"123@gmail.com"
}
文件2:
{
"name": "SES_ENABLED",
"value": "false"
},
{
"name":"SES_FROM_EMAIL",
"value":"xyz@gmail.com"
},
{
"name":"SES_ADDRESS",
"value":"emails-xyzyzyz.aws.com"
}
在上述两个文件中,名称变量将相同,但值不同,顺序也不同,并且文件1中还有一个额外的字段
即
{
"name": "SES_TO_EMAIL"
"value": "123@gmail.com"
}
如何从file1中比较存在的常见“名称”变量中的file2,并且如果file2中缺少比file1中的任何字段,我该如何获取。
例如:
将file1与file2比较之后,我需要获取文件{2中不存在"name": "SES_TO_EMAIL"
的输出。
任何解决方案都将非常有用。
先谢谢了:)
答案 0 :(得分:1)
假设每个文件都包含一个对象流,下面的简单jq程序就可以解决问题。
reduce inputs.name as $name ({}; .[input_filename] += [$name])
| (keys_unsorted | combinations(2)) as $pair
| (.[$pair[0]] - .[$pair[1]])[]
| "name: \(.) is not present in \($pair[1])"
调用:
jq -rnf prog.jq file1 file2 file3 ...
答案 1 :(得分:-1)
def compare(files):
# store all name into list of list
names = [[prop['name'] for prop in file] for file in files]
for i, name in enumerate(names):
# create a temporary list
temp_name = names.copy()
# remove current name in list
temp_name.pop(i)
for n in name:
for j, temp in enumerate(temp_name):
if not (n in temp): # if name in not present in the other file, print it
print('name: {} is not present in file {}'.format(n, (j+1 if j < i else j + 2)))
这是我的幼稚方式,我们需要将所有名称存储在list
中,并将每个名称与该列表进行比较。简单地使用它
import json
# open the first file
with open('file1.json', 'r') as file:
file1 = json.load(file)
# open the second file
with open('file2.json', 'r') as file:
file2 = json.load(file)
# then compare them
compare([file1, file2])
输出将是这样
name: SES_TO_EMAIL is not present in file 2