vendredi 6 juillet 2018

Python - If json element is "not valid", try the other one

So I have been playing around with Json and Python and basically I have a Json file where sometimes some elements are not included and sometimes it is. Basically what I want to do is that check if the first element that contains "ImageUrl" is there and is valid then use that element, Else use the other imageURL

"threads": [{
    "id": "3a64a3b18894fb70c92b6382a1e8f735320c1cbb",
    "product": {
        "imageUrl": "https://hello.com/555088_401.JPG",
    },
    "imageUrl": "https://hello.com/images/555088_401.JPG",
}]

However it can happen that the first ImageURL can contain 999999_999 at the end and that is counted as invalid aswell.

What I have done so far is:

resp = s.get(url)
item = resp.json()['threads']


    itempic = item.get('imageUrl')  # Check if there is sell date
    if itempic:
       image = str(item['imageUrl'])  # Image pic  

    else:
       print('Picture not found')

which currently only take the second url imageUrl which is not what I want but it does work (also it check if the imageUrl contains anything aswell), The question is:

How can I take the first imageUrl element and check if it is "valid" and does not contains 999999_999 at the end (If it is valid and correct then use it and print) else If it is not "valid" then use the second imageUrl

Aucun commentaire:

Enregistrer un commentaire