Home > OS >  Comparison of JSON file key values
Comparison of JSON file key values

Time:01-03

There are two JSON files with keys and values. You need to compare "key1" of two files and if the values are equal, then make a difference between the values of "key 2" of two files

file1.json

[
    {
        "key1": "KARA",
        "key2": "10"
    }
][
    {
        "key1": "SARA",
        "key2": "23"
    }
]

file2.json

{
    "code": 200,
    "data": [
        {
            "key1": "CRACK",
            "key2": "12"
        }
    ]
}{
    "code": 200,
    "data": [
        {
            "key1": "KARA",
            "key2": "13"
        }
    ]
}

That is, if the value of key 1 (file1.json) == the value of key1 (file2.json), it will be carried out: (file1.json) the value of key2 - (value2.json) the value of key2 (10 - 13)

Output to the terminal: -3

How can this be done?

I tried

with open('file1.json') as f, open('file2.json') as f2:
    json1 = json.load(f)
    json2 = json.load(f2)
if json1[0]['key1'] == json2['data'][0]['key1']:
    print(int(json1[0]['key2']) - int(json2['data'][0]['key2'])) # -3

It works if there is 1 object in the file, but not for the scenario I am asking about.

CodePudding user response:

You need to iterate over the lists:

with open('file1.json') as f, open('file2.json') as f2:
    json1 = json.load(f)
    json2 = json.load(f2)
for d1 in json1: 
    for d2 in json2: 
        if d1[0]['key1'] == d2['data'][0]['key1']: 
            print(int(d1[0]['key2']) - int(d2['data'][0]['key2']))

Output:

-3

CodePudding user response:

file1.json is invalid JSON as well as file2.json, it should be an object or array on the top level, e.g.:

# JSON 1
[
    {
        "key1": "KARA",
        "key2": "10"
    }, {
        "key1": "SARA",
        "key2": "23"
    }
]

# JSON 2
[{
    "code": 200,
    "data": [
        {
            "key1": "CRACK",
            "key2": "12"
        }
    ]
}, {
    "code": 200,
    "data": [
        {
            "key1": "KARA",
            "key2": "13"
        }
    ]
}]

Then there are many questions to ask and process:

  • Does len(json1) == len(json2)

Then you want to do something like:

with open('file1.json') as f, open('file2.json') as f2:
    json1 = json.load(f)
    json2 = json.load(f2)

json1_dict = {}
for json_obj in json1:
    json1_dict[json_obj['key1']] = int(json_obj['key2'])

json2_dict = {}
for json_obj in json2:
    json2_dict[json_obj['data'][0]['key1']] = int(json_obj['data'][0]['key2'])

for key in json1_dict:
    if key in json2_dict:
        print(f"diff: {json1_dict[key] - json2_dict[key]}")
  • Related