简体   繁体   中英

How do I print other parts of this json list in python?

First off I apologize if I use incorrect terms for any of this, I am just learning to use python and json.

I am trying to print the "name", "level", "class" and "experience" values out of this json code that I get from this code.

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

the output I get looks like this

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

but I would like for it to look like this

PenDora
100
Scion
4250334444

I have tried to add another for loop under the previous, but I get an error saying "TypeError: string indices must be integers"

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

What am I doing wrong here? Thank you in advance!

character['character'] is dictionary, so you don't iterate over it with for loop, but access it directly with key.

For example:

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

Prints:

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

... and so on.

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