如何在Python中使用列表推导收集json数据?

时间:2019-04-16 16:23:57

标签: python json

我是Python的新手,我无法使用列表推导从此json文件收集数据,但到目前为止它仍无法正常工作,那么如何构造此列表?我需要收集每种技能的tagName元素。

这是我尝试过的:

   def getUserSkills(handleList): #List of Strings
     for handles in handleList:
     response1 = requests.get("http://api.topcoder.com/v3/members/" +  handles + "/skills")
     data = response1.json()

     skillList = [skill['tagName'] for skill in data['result']['content']['skills']]

     print(skillList)

Json文件:

"id":"-462bfb3:16a2448d765:4ed3",
"result":{
  "success":true,
  "status":200,
  "metadata":null,
  "content":{
     "userId":21932422,
     "userHandle":"saarixx",
     "handleLower":"saarixx",
     "skills":{
        "130":{
           "tagName":"Brute Force",
           "hidden":false,
           "score":88.0,
           "sources":[
              "CHALLENGE"
           ]
        },
        "259":{
           "tagName":"JSON",
           "hidden":false,
           "score":5.0,
           "sources":[
              "CHALLENGE"
           ]
        },

2 个答案:

答案 0 :(得分:1)

遍历dct['result']['content']['skills']给出的字典并捕获value['tagName]

dct = {
    "id": "-462bfb3:16a2448d765:4ed3",
    "result": {
        "success": True,
        "status": 200,
        "metadata": None,
        "content": {
            "userId": 21932422,
            "userHandle": "saarixx",
            "handleLower": "saarixx",
            "skills": {
                "130": {
                    "tagName": "Brute Force",
                    "hidden": False,
                    "score": 88.0,
                    "sources": [
                        "CHALLENGE"
                    ]
                },
                "259": {
                    "tagName": "JSON",
                    "hidden": False,
                    "score": 5.0,
                    "sources": [
                        "CHALLENGE"
                    ]
                }
            }
        }
    }
}

skillList = [value['tagName'] for key,value in dct['result']['content']['skills'].items()]
print(skillList)
#['Brute Force', 'JSON']

答案 1 :(得分:0)

import requests


def getUserSkills(handleList):  # List of Strings
    data = []
    for handles in handleList:
        response = requests.get("http://api.topcoder.com/v3/members/" + handles + "/skills")
        data.append(response.json())
    skillList = [skill['tagName'] for skill in data['result']['content']['skills']]

    print(skillList)