Nogg
Nogg

Reputation: 9

How to use a list comprehension to collect json data in Python?

I am new to Python and I am having trouble collecting data from this json file using list comprehension but it is not working so far, so how I structure this list? I need to collect the tagName element of each skill.

This is what I tried:

   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 File:

"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"
           ]
        },

Upvotes: 0

Views: 920

Answers (2)

Umesh
Umesh

Reputation: 971

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)


Upvotes: 0

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Iterate through the dictionary given by dct['result']['content']['skills'] and capture 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']

Upvotes: 1

Related Questions