如何在函数中返回json响应并进行比较?

时间:2015-03-11 11:01:19

标签: python json python-2.7

所以基本上我得到了一个"返回外部功能"执行代码时出错。

我想要实现的是创建一个从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, "  ")

这就是我试图获得对象" ERROR"从

{
  "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"
}

1 个答案:

答案 0 :(得分:0)

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获取数据的简单方法。根据您的需要,您可以随时修改代码!