[英]decoding json dictionary with python
我已经编写了一个脚本来从 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 数据文件的代码。 谁能告诉我它有什么问题? 我仍然返回从“结果”词典的全部价值,这意味着它就像代码什么也没有做,我仍然得到完整的字典,它不会被解析,而不是只有“twitter_id”和“办公室”
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")
听起来你想要这样的东西:
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]
好的,查看 requests 模块的在线文档,我看到调用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'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.