1

is there a way to loop through two sets of JSON arrays and identify the additional array items from File 2 compared to File 1? Example below:

File 1:

{
    "Cars": [{
            "type": "Ford"
        },
        {
            "type": "BMW"
        }
    ]
}

File: 2

{
    "Cars": [{
            "type": "Ford"
        },
        {
            "type": "BMW"
        },
        {
            "type": "Vauxhall"
        },      
        {
            "type": "Fiat"
        }
    ]
}

Desired outcome:

The additons are:

{
        "Cars": [{
                "type": "Vauxhall"
            },      
            {
                "type": "Fiat"
            }
        ]
    }

I am struggling to get into the array in Python. Any help much appreciated.

2 Answers 2

1

If your data is this simple use in:

for c in y['Cars']:
  if c not in x['Cars']:
    print(c)

Or as a list comprehension:

diff_dict = {'Cars': [c for c in y['Cars'] if c not in x['Cars']]}

Output:

{'Cars': [{'type': 'Vauxhall'}, {'type': 'Fiat'}]}

You mentioned you were having a hard time getting the files into python. I used json.load()

Sign up to request clarification or add additional context in comments.

1 Comment

What if x array has the extra elements ? This will work only if he knows which one has extra elements.
1

Not sure if this is the most optimal or the finest method, but it should work

Assuming you've arrays as dict in python

a = []
b = []
for val in array1["Cars"]:
    a.append(val["type"])
for val in array2["Cars"]:
    b.append(val["type"])
diff = ( set(a) | set(b) ) - ( set(a) & set(b) )

You can iterate over diff and create json/dict in required format.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.