我已经编写了一个脚本来从API获取数据并返回它,但现在我需要解析该数据,这是json数据的样子的一个示例,我正在寻找一些字典值拉。
{'results': [{'icpsr_id': 21133,
'twitter_id': 'RepToddYoung',
'thomas_id': '02019',
'term_end': '2017-01-03',
'office': '1007 Longworth House Office Building',
'gender': 'M',
'phone': '202-225-5315',
这是我编写的代码,用于解析json数据文件。谁能告诉我它有什么问题?我仍然从'结果'字典中返回完整的值,这意味着它就像代码没有做任何事情,我仍然得到完整的字典,它没有被解析而不是 ONLY 'twitter_id'和'office'
import requests
import json
def call():
payload = {'apikey':'my_apikey', 'zip':'74120'}
bas_url = 'http://openstates.org/api/v1//legislators/?state=ok'
r = requests.get(bas_url, params = payload)
grab = r.json()
return grab
jsonResponse=json.loads(decoded_response)
jsonData = jsonResponse["results"]
for item in jsonData:
chamber = item.get("twitter_id")
last_name = item.get("office")
答案 0 :(得分:2)
听起来你想要这样的东西:
def call():
payload = {'apikey':'my_apikey', 'zip':'74120'}
bas_url = 'http://openstates.org/api/v1//legislators/?state=ok'
r = requests.get(bas_url, params = payload)
grab = r.json()
jsonData = grab["results"]
return [{key: value for key, value in result.items() if key in ("twitter_id", "office")} for result in jsonData]
答案 1 :(得分:0)
好的,查看请求模块的在线文档,我看到调用r.json()
将为您执行JSON解析,并返回一个Python dict。您发布的内容是该dict的输出,因此JSON部分已经为您处理。
使用json_response = r.json()
将数据提取到json_response后,此代码应该在Python 2和Python 3中都有效:
extracted_values = []
json_data = json_response['results']
for item in json_data:
subitem_dict = {}
for key in 'twitter_id office'.split():
subitem_dict[key] = item.get(key) # will give None if key does not exist
extracted_values.append(subitem_dict)
print(extracted_values)
打印:
[{'twitter_id': 'RepToddYoung', 'office': '1007 Longworth House Office Building'},
{'twitter_id': 'SenDonnelly', 'office': '720 Hart Senate Office Building'},
{'twitter_id': 'SenDanCoats', 'office': '493 Russell Senate Office Building'}]