0

I arrive to retrieve JSON from Yelp API. Problems arrive when I search for a town but that town is not in Yelp database. In this case I receive a response:

{
  "error": {
    "code": "LOCATION_NOT_FOUND",
    "description": "Could not execute search, try specifying a more exact location."
  }
}

As I'm searching in bulk I would like to write a statement that says that if "LOCATION_NOT_FOUND" is inside my JSON response, do nothing and pass to the next town.

I need something like this:

if response_data['error']['code'] == 'LOCATION_NOT_FOUND':
    pass
else:

but is not working because it says:

if response_data['error']['code'] == 'LOCATION_NOT_FOUND':
KeyError: 'error'

this because error is not always there but just when there is no town

Francesco Mantovani
  • 10,216
  • 13
  • 73
  • 113

1 Answers1

1

You need to first check if there is an error. This can be done using the key in dict syntax.

if 'error' in response_data:  # Check if there is a key called "error"
    if response_data['error'].get('code') != 'LOCATION_NOT_FOUND':
        # A different code, should probably log this.
        logging.error(json.dumps(response_data))
else:
    # Continue as normal.
Artyer
  • 31,034
  • 3
  • 47
  • 75