Home > Mobile >  How to get nested JSON file
How to get nested JSON file

Time:01-08

I'm trying to make a warning system in discord bot, but before it I trying to make RAW code of it. The structure I already know, but when it goes to JSON file I don't know more The part that I confused is at here

checkname = any(d['USER ID'] == id_card for d in json_load['user_id'])
if checkname == True:
    print(json_load['user_id']['WARN STATUS'])
if checkname == False:
    write_json(dump_data)

And this is my JSON file

{
    "guild_configuration": {
        "guild_ids": [
            11111111111111
        ],
        "token": "SENSOR"
    },
    "user_id": [
        {
            "USER ID": "385053392059236353",
            "USERNAME": "MorpKnight",
            "WARN STATUS": "Unwarned",
            "WARNING": 0
        },
        {
            "USER ID": "128418907681764",
            "USERNAM": "TESTING",
            "WARN STATUS": "WARNED",
            "WARNING": 1
        }
    ]
}

I firstly I know I need to check the USER ID is the person that I warned or no. Then I need to check about "WARNING" and "WARN STATUS" but I don't know how? Any idea?

CodePudding user response:

A simple solution would be to iterate over the elements in the user_id list and then break when you have a match for the USER ID. This assumes that user IDs are unique, which I believe is the case for Discord. I've tried to match the logic in the snippet as close as possible, but since you haven't given values for some of the variables (and syntactially it isn't quite right, as you need to provide an integer index for indexing json_load['user_id']) it may not be perfect:

found_user = True
for user in json_load['user_id']:
    if user['USER ID'] == id_card:
        print(user['WARN STATUS'])
        found_user = True
        break

if not found_user:
    write_json(dump_data)

CodePudding user response:

Search the USER ID , if it's there get the warn status. Otherwise dump the json.

warn_status = next(
    (user['WARN STATUS'] for user in json_load['user_id']
     if user['USER ID'] == id_card), None)
if warn_status:
    print(json_load['user_id']['WARN STATUS'])
else:
    write_json(dump_data)
  •  Tags:  
  • Related