0

My code:

r = requests.get('http://localhost:5000/players')

j = json.loads(r.text)["items"][0]["nickname"]
print(j)

player A

j = json.loads(r.text)["items"][1]["nickname"]

print(j)

player B

My JSON:

{
  "total_count": 2,
  "items": [
    {
      "nickname": "player A",
      "Game": "COD",
      "score": 1.0
    },
    {
      "nickname": "player B",
      "Game": "Tetris",
      "score": 1.1
    }
  ]
}


I wanted a way to print all "nickname". I tried a for but I do not know how to loop [0][1][3][4]..

For example: for key in j: print(key, 'd', j[key])

haxkkroto
  • 72
  • 1
  • 6
  • You can instead loop over the json ``for x in json.loads(r.text)["items"]:x['nickname']`` – sushanth Jun 06 '20 at 10:49
  • Does this answer your question? [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – sushanth Jun 06 '20 at 10:51

1 Answers1

2

Note that json.loads(r.text)["items"] is a list and you can iterate over it.

j = json.loads(r.text)["items"]
for i in range(len(j)):
    print(j[i]["nickname"])

Alternately, as @Sushanth mentions in the comment, you can use a for each loop:

j = json.loads(r.text)["items"]
for i in j:    # iterates over j, assigning the values to i
    print(i["nickname"])
Ankit Kumar
  • 1,145
  • 9
  • 30