简体   繁体   English

Python&Yelp API:如何绕过JSON响应LOCATION_NOT_FOUND

[英]Python & Yelp API: how to bypass JSON response LOCATION_NOT_FOUND

I arrive to retrieve JSON from Yelp API. 我到达从Yelp API检索JSON。 Problems arrive when I search for a town but that town is not in Yelp database. 当我搜索城镇时,问题就出现了,但是该城镇不在Yelp数据库中。 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. 在批量搜索时,我想写一条语句,说if JSON响应中包含“ LOCATION_NOT_FOUND”,则不执行任何操作并传递到下一个城镇。

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 这是因为错误并不总是存在,而只是在没有城镇时

You need to first check if there is an error. 您需要先检查是否有错误。 This can be done using the key in dict syntax. 这可以使用key in dict语法中的key in dict来完成。

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM