Skip to content
Advertisement

Checking a dictionary key name, which is an instance of a class

I am using a module called jsondiff to compare changes between two json files. When a change is detected it returns a dictionary. The dictionary keys are instances of a class from the module.

Depending on the type of change (something new added, deleted or changed), the dictionary keys are named differently but appear to be an instance of the same class

I am trying to check if the instance is equal to a certain type of change. How can I write a conditional to check the name of the key?

Here is an example: json file 1

[{
    "first": "John",
    "last": "Smith",
    "membership": "general"
},
{
    "first": "Jane",
    "last": "Dogood",
    "membership": "VIP"
}]

json file 2

[{
    "first": "John",
    "last": "Smith",
    "membership": "VIP"
 },
 {
    "first": "Jane",
    "last": "Dogood",
    "membership": "VIP"
 },
 {
    "first": "Robert",
    "last": "Jones",
    "membership": "VIP"
 }]

Python code

with open("/file1.json") as f1, open("/file2.json") as f2:
    data1 = json.load(f1)
    data2 = json.load(f2)

changes = jsondiff.diff(data1, data2)

for key, val in changes.items():
    print(key, val)
    print(type(key))
    if key == "insert": # also tried "$insert", and insert without quotes
      # Do something

Output:

0 {'membership': 'VIP'}
<class 'int'>
$insert [(2, {'first': 'Robert', 'last': 'Jones', 'membership': 'VIP'})]
<class 'jsondiff.symbols.Symbol'>

Advertisement

Answer

The key is of type jsondiff.symbols.Symbol, and you can check that directly.

    if key == jsondiff.symbols.insert:
        #do something

When the key is printed we know it returns $insert. This means it has a str representation. We can get that representation by wrapping the key in str.

    if str(key) == "$insert":
        #do something

jsondiff.symbols.py

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement