简体   繁体   中英

How to Iterate over JSON object or dictionary

I'm new to Python and I'm having trouble with a Json object. What would be the best way to do this iteration? I need to collect the Rank of all users)

//JSON file

"total": 2702,
"pageIndex": 1,
"pageSize": 100,
"data": [
  {
  "rank": 1,
  "handle": "saarixx",
  "color": "Red",
  "rating": 3249,
  "highestRatingType": "Design"
},
{
  "rank": 2,
  "handle": "kyky",
  "color": "Red",
  "rating": 2785,
  "highestRatingType": "Design"
},
{
  "rank": 3,
  "handle": "dmks",
  "color": "Red",
  "rating": 2575,
  "highestRatingType": "Design"
},

//What I tried

 response = requests.get("https://api.topcoder.com/v2/users/tops/develop/", params=pages)
 data = json.loads(response.text)

for i in data.items():
    print(data['data'][i]['rank'])

Use a simple list comprehension:

[user['rank'] for user in data['data']]

Output:

[1, 2, 3]

A couple of different ways to do this, loop, list comprehension or my new favorite (and probably overkill) Pandas DataFrame.

import requests
import pandas as pd

response = requests.get("https://api.topcoder.com/v2/users/tops/develop/")
data = response.json()

player_stats = data['data']

player_stats_df = pd.DataFrame(player_stats)

player_stats_df

The above code generates a nice structured table. 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM