簡體   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