2

I've the following json file (banneds.json):


{
  "players": [
    {
      "avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/07/07aa315f664efa92456569429230bc2c254c3ff8_full.jpg",
      "created": 1595050663,
      "created_by": "<@128152620136267776>",
      "nick": "teste",
      "steam64": 76561198046619692
    },
    {
      "avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/21/21fa5c468597e9c890212b2e3bdb0fac781c040c_full.jpg",
      "created": 1595056420,
      "created_by": "<@128152620136267776>",
      "nick": "ingridão",
      "steam64": 76561199058918551
    }
  ]
}

And I want to insert new values if the new value (inserted by user) is not already in the json, however when I try to search if the value is already there I receive a false value, an example of what I'm doing ( not the original code, only an example ):

import json

check = 76561198046619692
with open('banneds.json', 'r') as file:
    data = json.load(file)
if check in data:
    print(True)
else:
    print(False)

I'm always receiving the "False" result, but the value is there, someone can give me a light of what I'm doing wrong please? I tried the entire night to find a solution, but no one works :(

Thanks for the help!

edufgimenez
  • 60
  • 1
  • 3
  • 9

2 Answers2

4

You are checking data as a dictionary object. When checking using if check in data it checks if data object have a key matching the value of the check variable (data.keys() to list all keys).

One easy way would be to use if check in data["players"].__str__() which will convert value to a string and search for the match.

If you want to make sure that check value only checks for the steam64 values, you can write a simple function that will iterate over all "players" and will check their "steam64" values. Another solution would be to make list of "steam64" values for faster and easier checking.

Emin Mastizada
  • 1,375
  • 2
  • 15
  • 30
  • Thanks for the help, I followed your idea and created a list and append all steam64 values to this list, after that I used 'in' to verificate. All works fine now. – edufgimenez Jul 18 '20 at 17:15
3

You can use any() to check if value of steam64 key is there.

For example:

import json


def check_value(data, val):
    return any(player['steam64']==val for player in data['players'])

with open('banneds.json', 'r') as f_in:
    data = json.load(f_in)

print(check_value(data, 76561198046619692))

Prints:

True
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91