如何遍历JSON对象或字典

时间:2019-04-11 23:21:29

标签: python json api

我是Python的新手,我在使用Json对象时遇到了麻烦。进行此迭代的最佳方法是什么?我需要收集所有用户的排名

// JSON文件

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

//我尝试过的

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

2 个答案:

答案 0 :(得分:1)

使用简单的list理解:

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

输出:

[1, 2, 3]

答案 1 :(得分:0)

执行此操作的两种不同方法是循环,列表理解或我最喜欢的(可能是过大的)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

上面的代码生成一个漂亮的结构化表。 enter image description here