-2

I have a array of JSON in which i want to find whether a part of json is present or not.

For eg: I have this array of json:

a = [{'a':'xxxx','b':'yyyy'},{'a':'xzxzxz','b':'asqqqq'}]

And I want to know if a = 'xxxx' is present in the array or not?

I have tried this:

if {'a':'xxxx'} in a:
    print('1') 
else:
    print('2')

But it is giving me '2'

How to do this. Thanks!

P.S: I don't want to use a FOR LOOP

Harshit verma
  • 506
  • 3
  • 25
  • 3
    What you want is to test whether any dict in your list has a key with a specific value; nothing to do with "JSON". `any(d['a'] == 'xxxx' for d in a)` – deceze Feb 12 '20 at 13:11
  • First, you have to iterate over every JSON(dict), that's included in your array. Then you can check, if the dict contains a key and if, check its value. – Mig B Feb 12 '20 at 13:11
  • @deceze it will raise an exception if `'a'` is not present in the dict – Tal Feb 12 '20 at 13:13
  • @Tal If that's a concern, use `d.get('a')` then. – deceze Feb 12 '20 at 13:14

2 Answers2

1

You can use any for testing and I would use .get in case not all your dict elements have the a key, for example this:

a = [{'a':'xxxx','b':'yyyy'},{'a':'xzxzxz','b':'asqqqq'}]

if any(dct.get('a', None) == 'xxxx' for dct in a):
    print(1)
else:
    print(2)

marcos
  • 4,473
  • 1
  • 10
  • 24
0

Your code prints '2' because {'a':'xxxx'} is not present in a.
That is because {'a':'xxxx','b':'yyyy'} is not equal to {'a':'xxxx'}.

You will have to write a function like this:

def has_a(array):
    for item in array:
        if item.get('a') == 'xxxx':
            return True
    return False

and then use it like this:

if has_a(a):
    print('1') 
else:
    print('2')
Tal
  • 548
  • 3
  • 8