如何在python中打印此json列表的其他部分?

时间:2019-12-10 22:36:09

标签: python json

首先我很抱歉,如果我对此使用不正确的术语,我只是在学习使用python和json。

我正在尝试从我从此代码中获得的json代码中打印“名称”,“级别”,“类”和“经验”值。

pathAPI = requests.get("http://api.pathofexile.com/ladders/Standard?limit=10")
data = json.loads(pathAPI.text)
print(data) 
for character in data['entries']:
    print('============================================================')
    print("Rank: ", character["rank"])
    print(character['character'])  

我得到的输出看起来像这样

Rank:  1
{'name': 'PenDora', 'level': 100, 'class': 'Scion', 'id': 'cc248e0d23c849d71b40379d82dfc19b200bdb7b8ac63322f06de6483aaca5ea', 'experience': 4250334444}

但是我希望它看起来像这样

PenDora
100
Scion
4250334444

我曾尝试在前一个下添加另一个for循环,但出现一条错误消息“ TypeError:字符串索引必须为整数”

pathAPI = requests.get("http://api.pathofexile.com/ladders/Standard?limit=10")

data = json.loads(pathAPI.text)
print(data) 
for character in data['entries']:
    print('============================================================')
    print("Rank: ", character["rank"])
    print(character['character'])    
    for playerInfo in character['character']:
        print(playerInfo['name'])
        print(playerInfo['level'])
        print(playerInfo['class'])
        print(playerInfo['experience'])

我在这里做错了什么?预先谢谢你!

1 个答案:

答案 0 :(得分:4)

character['character']是字典,因此您不必使用for循环对其进行迭代,而是直接使用key对其进行访问。

例如:

import requests

data = requests.get("http://api.pathofexile.com/ladders/Standard?limit=10").json()

for character in data['entries']:
    print('============================================================')
    print("Rank: ", character["rank"])
    print(character['character']['name'])
    print(character['character']['level'])
    print(character['character']['class'])
    print(character['character']['experience'])

打印:

============================================================
Rank:  1
PenDora
100
Scion
4250334444
============================================================
Rank:  2
TaylorSwiftVEVO
100
Scion
4250334444
============================================================

... and so on.