Bradley D. Freeman-Bain Bradley D. Freeman-Bain - 7 months ago 31
Python Question

parsing json dictionary with python

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',





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")

Answer

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 jsonData.items() if key in ("chamber", "last_name")}