Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to determine if json object contains a certain value?

I have a json object I get returned from a call, similar to this:

{
    'Tags': [
        {
            'Key': 'Dept',
            'PropagateAtLaunch': True,
            'ResourceId': 'my-auto-scaling-group',
            'ResourceType': 'auto-scaling-group',
            'Value': 'Research',
        },
        {
            'Key': 'Role',
            'PropagateAtLaunch': True,
            'ResourceId': 'my-auto-scaling-group',
            'ResourceType': 'auto-scaling-group',
            'Value': 'WebServer',
        },
        {
            'Key': 'ecs_scaling',
            'PropagateAtLaunch': True,
            'ResourceId': 'my-auto-scaling-group',
            'ResourceType': 'auto-scaling-group',
            'Value': 'true',
        },
    ],
    'ResponseMetadata': {
        '...': '...',
    },
}

Is there a more Pythonic way of simply determining whether or not the Key ecs_scaling exists, other than the standard:

data = json.loads(theThing)
for key in data.items():
   ... 

The Key could be the first item, it could be the 40th item -- ideally I'd like to be able to do something like if 'ecs_scaling' in theKeys: ... ?

like image 664
MrDuk Avatar asked Aug 30 '17 15:08

MrDuk


People also ask

How do you check if a json object contains a key or not?

Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().

How do you check if a value exists in a json string in Python?

One easy way would be to use if check in data["players"]. __str__() which will convert value to a string and search for the match. If you want to make sure that check value only checks for the steam64 values, you can write a simple function that will iterate over all "players" and will check their "steam64" values.

How do you check if a key is present in json or not Python?

Check if the key exists or not in JSON Note: We used json. loads() method to convert JSON encoded data into a Python dictionary. After turning JSON data into a dictionary, we can check if a key exists or not.

How do you Analyse json data in Python?

Instead of the JSON loads method, which reads JSON strings, the method used to read JSON data in files is load(). The load() method takes up a file object and returns the JSON data parsed into a Python object. To get the file object from a file path, Python's open() function can be used.


3 Answers

You can use the builtin any.

Return True if any element of the iterable is true. If the iterable is empty, return False.

if any(tag['key'] == 'ecs_scaling' for tag in data['Tags']):
    ...
like image 148
Zach Gates Avatar answered Oct 04 '22 04:10

Zach Gates


The complexity is already linear, so the only faster thing that you could hope for is a hash search. However, constructing a hash set or a hash table would require a linear complexity.

So unless the functions you call from the json module already build such a hash set, an iteration is the best thing you can do, for a linear complexity, ie O(n).

In this regard, I think the most Pythonic approach is using the any built-in, already mentioned by the other.

For the sake of completeness, although it would be less performant, you could go with a list comprehension as well, which is often considered as "highly Pythonic":

'ecs_scaling' in [item['Key'] for item in data.items()]

This is not as good, because an additional list has to be constructed, which requires an iteration over the whole data.

like image 35
Right leg Avatar answered Oct 04 '22 04:10

Right leg


any(el['Key'] == 'ecs_scaling' for el in data['Tags'])
like image 20
Ignacio Vazquez-Abrams Avatar answered Oct 04 '22 03:10

Ignacio Vazquez-Abrams