PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 24, 2022

[FIXED] How to print specific json data for multiple instances?

 July 24, 2022     discord.py, json, python     No comments   

Issue

import requests

url = "https://api.gametools.network/bf1/players/?gameId=7218126050214"
r = requests.get(url)
data = r.json()
print(data['teams'][1]['players'][0]['name'])
print(data['teams'][1]['players'][1]['name'])
print(data['teams'][1]['players'][2]['name'])
print(data['teams'][1]['players'][3]['name'])
print(data['teams'][1]['players'][4]['name'])
print(data['teams'][1]['players'][5]['name'])
print(data['teams'][1]['players'][6]['name'])
print(data['teams'][1]['players'][7]['name'])
print(data['teams'][1]['players'][8]['name'])
print(data['teams'][1]['players'][9]['name'])
print(data['teams'][1]['players'][10]['name'])
print(data['teams'][1]['players'][11]['name'])
print(data['teams'][1]['players'][12]['name'])
print(data['teams'][1]['players'][13]['name'])
print(data['teams'][1]['players'][14]['name'])
print(data['teams'][1]['players'][15]['name'])
print(data['teams'][1]['players'][16]['name'])
print(data['teams'][1]['players'][17]['name'])
print(data['teams'][1]['players'][18]['name'])
print(data['teams'][1]['players'][19]['name'])
print(data['teams'][1]['players'][20]['name'])

This is a snippet of my code that I think could be really improved to save some space, the issue is I can't seem to find a way to enumerate all the players name beside doing them one per one like shown above, my goal is to have a list that will show every username for both team of a given server.

I should mention the code is currently working but I feel like there is a much simpler way to obtain the data I need, I did search for these methods but because my data is nested in a list/dictionary I get confused.

Any suggestion is welcome, thank you :)


Solution

Here is how to iterate over a list:

l = [1, 2, 3, 4]

for element in l:
    print(l)

Once you know that, it's only a matter of breaking nested iteration problems down to their simplest form above. So you just need to get the list which you need to iterate over, and then use the above sample you already know:

l = data['teams'][1]['players']
for element in l:
    print(element['name'])


Answered By - Charchit
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing