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!
['foo']to get the element at'foo'from a dictionary, it will raise a KeyError if that element isn't found. If instead you used.get('foo')then that method will returnNone(or another default value you provide) if the key'foo'isn't found. Using that, you can remove the try-except block by checking if the return value fromgetis None or not. I can write up an example if needed.