Python -check if a key:value pair exists at least once in a nested json object

Viewed 67

I've got a JSON-object looking like this: enter image description here

I want to check if one of the given prices ({0} , {1} , {2}) contains priceType == "04" and countriesIncluded == "DE"

My code:

r = requests.get(f'https://api.vlb.de/api/v2/product/{isbn}/ean?access_token=9xx9xxxxxc9')
        vlb = json.loads(r.text)
        for i in vlb['prices']:
            if i['priceType'] == "04" and i["countriesIncluded"] == "DE":
                neupreis = i['priceAmount']
            else:
                neupreis = "False"

The problem with my attempt is the following: neupreis will always get the value of the last price (in this case {2} where the condition is false) but I want to check if any of the prices meet the condition.

Is there a better way to search through a JSON object than the for-loop I'm using?

PS: I've found some similar questions on Stack Overflow, but none of those Json-objects were as nested as mine… Thank you!

2 Answers

Using your code, if I understand you correctly, you could just do something like this:

r = requests.get(f'https://api.vlb.de/api/v2/product/{isbn}/ean?access_token=9xx9xxxxxc9')
vlb = json.loads(r.text)

neupreis = "False"
for i in vlb['prices']:
    if i['priceType'] == "04" and i["countriesIncluded"] == "DE":
        neupreis = i['priceAmount']
        break

A different approach would be to use a list-comprehension like this:

neupreise = [i['priceAmount'] for i in vlb["prices"] if i['priceType'] == "04" and i["countriesIncluded"] == "DE"]

In this case all the priceAmounts for the prices that meet the criterium are saved in a list. If the list is empty, then none of them met the criterium.

This should help if you want to check if you don't want the last forloop to silently do nothing you can add before the second loop if indexes:

r = requests.get(f'https://api.vlb.de/api/v2/product/{isbn}/ean?access_token=9xx9xxxxxc9')
    vlb = json.loads(r.text)
    indexes=[]
        for i, preisDict in enumerate(vlb['prices']):
            if preisDict['priceType'] == "04" and preisDict["countriesIncluded"] == "DE":
                #neupreis = preisDict['priceAmount']
                indexes.append(i)
# Now you can access the Prices which meets the condition using
for i in indexes: # Will silently do nothing if the is not any which matches the condition
    vlb['prices'][i] # then do something with the right pricetypes
Related