decoding json dictionary with python

后端 未结 2 615
小鲜肉
小鲜肉 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

    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'}]
    

提交回复
热议问题