【问题标题】:How to return a json response in a function and compare it?如何在函数中返回json响应并进行比较?
【发布时间】:2015-03-11 11:01:19
【问题描述】:

所以基本上我在执行代码时遇到“返回外部函数”错误。

我想要实现的是创建一个从 API 获取 JSON 响应的函数,然后我可以将该响应与一个字符串进行比较,以插入一些相同的文本。

这是我的代码。

def res():
  api = "http://football-api.com/api/?Action=competitions&APIKey=aade7b79-af8b-9908-ad990d651a08&comp_id=1204"
  respobj = requests.get(api)
  adict = respobj.json()
  theresponse = adic['ERROR'] 
return theresponse

if(res()) == "no matches found today":
   output.insert(END, "There no premier leauge matches today")
else:
 # Grab todays matches and scores from the API
   output.insert(END, "  ")

这是我试图从中获取对象“错误”的 api 响应

{
  "APIVersion": 1,
  "APIRequestsRemaining": 983,
  "DeveloperAuthentication": "TRUE",
  "Action": "today",
  "Params": {
    "Action": "today",
    "APIKey": "aade7b79-af8b-9908-ad990d651a08",
    "comp_id": "1204"
  },
  "ComputationTime": 0.079131126403809,
  "IP": "**********",
  "ERROR": "no matches found today",
  "ServerName": "Football-API",
  "ServerAddress": "http://football-api.com/api"
}

【问题讨论】:

  • 请修复缩进...并返回外部函数可能意味着您的代码中有非缩进返回...
  • 我可以使用任何资源来弄清楚我应该如何正确缩进我的代码?我只是这里的初学者。
  • 这个可能会帮助你:diveintopython.net/getting_to_know_python/indenting_code.html 但除了谷歌之外,还有很多资源涵盖了基础知识。如果您完全不熟悉它,建议您做一些教程。
  • 我修复了缩进,但现在该函数没有返回任何内容。
  • 您需要的第一步是通过 url 解析 urllib.. 将其存储在 var 中,然后使用 json.loads 并像 var['ERROR'] 一样访问

标签: python json python-2.7


【解决方案1】:
def res(self):
    request_url = "http://football-api.com/api/?Action=competitions&APIKey=aade7b79-af8b-9908-ad990d651a08&comp_id=1204"

    parse_url = urllib.urlopen(request_url).read()

    raw_data = json.dumps(parse_url)
    json_data = json.loads(raw_data)

if (json_data['ERROR']):
    //do something

这是从 API 获取数据的简单方法。根据你的需要,你可以随时修改代码!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 2020-10-11
    • 2021-10-17
    • 2015-04-11
    相关资源
    最近更新 更多