decoding json dictionary with python

后端 未结 2 617
小鲜肉
小鲜肉 2021-01-29 14:21

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 dicti

相关标签:
2条回答
  • 2021-01-29 14:24

    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]
    
    0 讨论(0)
  • 2021-01-29 14:24

    Ok, looking at the online docs for the requests module, I see that calling r.json() will do the JSON parsing for you, and give you back a Python dict. The thing you are posting is the output of that dict, so the JSON part has already been taken care of for you.

    This code should work in both Python 2 and Python 3, once you have extracted the data to json_response using json_response = r.json():

    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)
    

    prints:

    [{'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'}]
    
    0 讨论(0)
提交回复
热议问题