繁体   English   中英

比较两个文件中同名但值不同的两个 json 文件

[英]Compare two json files with same name but different values in two files

我有两个 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 中还有一个额外的字段

IE

{
   "name": "SES_TO_EMAIL"
   "value": "123@gmail.com"
}

从file1我如何比较file2中常见的“名称”变量,以及如果file2中缺少任何字段而不是file1,我怎么能得到它。

例如:

在将file1与file2进行比较后,我需要得到output,如"name": "SES_TO_EMAIL"

任何解决方案都会非常有用。

提前致谢:)

假设每个文件都包含一个 stream 对象,一个简单的程序就可以解决问题。

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 ...
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])

output 将是这样的

name: SES_TO_EMAIL is not present in file 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM