用python解码json字典 [英] decoding json dictionary with python

查看:130
本文介绍了用python解码json字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个脚本来从API提取数据并返回它,但是现在我需要解析该数据,这是json数据的示例,其中包含一些我希望查找的字典值拉.

Ive got a script written to fetch data from an API, and return it, but now i need to parse that data, this is an example of what the json data looks like, with some of the dictionary values i am looking to pull.

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


this is the code i have written to pull, and parse the json data file. could anyone tell me what is wrong with it? i am still returning the full value from the 'results' dictionary, Meaning it's like the code has done nothing, i still get the full dictionary, it isn't parsed instead of ONLY the 'twitter_id', and '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")

推荐答案

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

It sounds like you want something like this:

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]

这篇关于用python解码json字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆