CDNthe2nd
CDNthe2nd

Reputation: 369

Python - How to continue if json element not found

So I have been playing around with Json and some comparing.

So basically I have a Json where some element are included in some elements and some don't.

The issue I am having is that the script continues the script over and over but never does anything due to exception where it can't find the elements etc Price, estimatedLaunchDate which will be found in this Json

sample = {
"threads": [{
        "seoTitle": "used food",
        "other_crap": "yeet"
    },
    {
        "seoTitle": "trucks",
        "other_crap": "it's a fox!"
        "product": {
            "imageUrl": "https://imagerandom.jpg",
            "price": {
                "fullRetailPrice": 412.95
            },
            "estimatedLaunchDate": "2018-06-02T03:00:00.000",
            "publishType ": "DRAW"
        },
        {
            "seoTitle": "rockets",
            "other_crap": "i'm rocket man"
        },
        {
            "seoTitle": "helicopter",
            "other_crap": "for 007"
            "product": {
                "imageUrl": "https://imagerandom.jpg",
                "price": {
                    "fullRetailPrice": 109.95
                },
                "estimatedLaunchDate": "2018-06-19T00:00:00.000",
                "publishType": "FLOW"
            }
        }
    ]
}

as you can see there is some extra information in some of the json elements than the other and there is the issue I am having, What/how can I make it so it continues or just adds etc "Price not found", "publishType not found" and still continue the rest of the json?

I have made a code that does this so far:

old_list = []

    while True:
        try:
            resp = requests.get("www.helloworld.com")
            new_list = resp.json()['threads']

            for item in new_list:

                newitemword = item['seoTitle']

                if newitemword not in old_list:
                    try:

                        print(newitemword) #item name

                        print(str(item['product']['price']['fullRetailPrice']))
                        print(item['product']['estimatedLaunchDate']) 
                        print(item['product']['publishType']) 


                        old_list.append(newitemword)



                    except Exception as e:
                        print(e)
                        print("ERROR")
                        time.sleep(5)
                        continue


            else:
                randomtime = random.randint(40, 60)
                time.sleep(randomtime)

As you can see there is 4 prints inside the try except method and if one of those 3 (fullRetailPrice, estimatedLaunchDate, publishType) it will throw a exception and will not continue the rest of the code meaning it will already die after the "seoTitle": "trucks", element!

Upvotes: 2

Views: 3661

Answers (1)

BowlingHawk95
BowlingHawk95

Reputation: 1648

I won't rewrite your whole example, but suppose that when you lookup the value

print(str(item['product']['price']['fullRetailPrice']))

one or more of those keys you follow might not be there. You could detect this in code by doing

foo = item.get('product', {}).get('price', {}).get('fullRetailPrice')
if foo:
    print(str(foo))
else:
    print('Retail price could not be found')

The second parameter to get is the value to return if the desired key can't be found. Making this return an empty dictionary {} will let you keep checking down the line until the end. The last get will return None if any of the keys aren't found. You can then check if foo is None and print an error message appropriately.

Upvotes: 4

Related Questions