【问题标题】:decoding json dictionary with python用python解码json字典
【发布时间】:2016-05-02 23:49:35
【问题描述】:

我已经编写了一个脚本来从 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")

【问题讨论】:

  • call() 因为return grab 而提前退出,所以之后的一切都不会发生。
  • 那么,我应该完全删除返回抓取吗?或者,只是将其移到其余部分下方?
  • 这取决于你想让你的函数做什么。
  • 对不起,我发布了多个问题,试图理解这一点并使用正确的术语,但我想我一直在使用误导人们的不正确术语。看看这是否使我想要的更清楚,然后也许你会有答案。 stackoverflow.com/questions/36994928/…
  • 多次发布同一个问题在 SO 中是非常不受欢迎的。坚持一个问题并添加编辑。否则整个数据库将充满零散的讨论,对任何人都没有用。

标签: python json parsing


【解决方案1】:

听起来你想要这样的东西:

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]

【讨论】:

  • thaaaannnkkkk 你!
  • 实际上'results'的值似乎是一个列表,所以你可能想要return [{key: value for key, value in x.items() if key in ("twitter_id", "office")} for x in jsonData['results']]
  • @alykhank 你是对的,没有正确考虑。
  • Traceback(最近一次调用最后一次):文件“”,第 1 行,在 文件“/home/brad/Documents/congress.py”,第 8 行,调用抓取中= r.json() 文件“/usr/lib/python3/dist-packages/requests/models.py”,第 808 行,在 json 中
  • return complexjson.loads(self.text, **kwargs) File "/usr/lib/python3.5/json/__init__.py", line 319, in loading return _default_decoder.decode(s ) 文件“/usr/lib/python3.5/json/decoder.py”,第 339 行,在 decode obj 中,end = self.raw_decode(s, idx=_w(s, 0).end()) 文件“/ usr/lib/python3.5/json/decoder.py",第 357 行,在 raw_decode
【解决方案2】:

好的,查看 requests 模块的在线文档,我发现调用 r.json() 将为您进行 JSON 解析,并返回一个 Python 字典。您发布的内容是该 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'}]

【讨论】:

    猜你喜欢
    • 2013-06-30
    • 1970-01-01
    • 2021-07-09
    • 2022-07-29
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多