Wolfmann Games
Wolfmann Games

Reputation: 150

How to print specific data from json file?

So I am making a stat bot for one of my favourite games. I can print the overall stats but not the stats for each game mode. The problem is that all the stats are in an array I thing and I don't know how to print things from them? How do I print specific things this?

My code:

import json
import requests


def stats(name):
    global r
    headers = {'content-type': 'application/json; charset=UTF-8'}
    url = 'https://surviv.io/api/user_stats'
    payload = {"slug": name, "interval": "all", "mapIdFilter": "-1"}
    r = requests.post(url=url, headers=headers, data=json.dumps(payload))
    c = r.json()
    kills = str(c["kills"])
    wins = str(c["wins"])
    games = str(c["games"])
    kg = str(c["kpg"])
    mostkills = str(max([i["mostKills"] for i in c["modes"]]))
    maxdamage = str(max([i["mostDamage"] for i in c["modes"]]))
    print("Overall")
    print("Kills:", kills)
    print("Wins:", wins)
    print("Games:", games)
    print("K/G:", kg)
    print("Most Damage:", mostkills)
    print("Max Damage:", maxdamage)
    print()
    print("Content")
    print(c)


stats(name="beep")

Output

enter image description here

As you can see, I want to separate them. teamMode 1 is solos, teamMode 2 is duos and teamMode 3 is squads

Upvotes: 0

Views: 317

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54812

This should give you a good start.

for team in c['modes']:
    print( "Mode: ", team['teamMode'] )
    print( "  Games: ", team['games'] )
    print( "  Wins:  ", team['wins'] )
    print( "  Kills: ", team['kills'] )

Or, if you just want "mostKills" from the second entry:

print( c['modes'][1]['mostKills'] )

Upvotes: 1

Related Questions