Class-Corder / utils.py
utils.py
Raw
import json
import uuid

def generate_uuid():
    generate_id = lambda: uuid.uuid4().hex
    return generate_id()

def check_login(st):
  if st.session_state.get("status", "unverified") != "verified" or len(st.session_state.get("username", "")) < 2:
    st.switch_page("auth.py")

def json_validator(raw_text, keys, outer_key=None):
    try:
        data = json.loads(raw_text)  # Attempt to parse the JSON
    except json.JSONDecodeError:
        print("Invalid JSON: The string could not be decoded.")
        return False
    
    if outer_key:
        # Check if the outer_key is in the data and it's a list
        if outer_key not in data or not isinstance(data[outer_key], list):
            print(f"Invalid JSON: '{outer_key}' must be present and be a list.")
            return False
        
        # Validate each item in the list under the outer_key
        for item in data[outer_key]:
            if not isinstance(item, dict):
                print("Invalid JSON: Each item in the list must be a dictionary.")
                return False
            if not all(key in item for key in keys):
                missing_keys = [key for key in keys if key not in item]
                print(f"Invalid JSON: Missing keys {missing_keys} in some items.")
                return False
    else:
        # Validate the keys directly in the main dictionary
        if not all(key in data for key in keys):
            missing_keys = [key for key in keys if key not in data]
            print(f"Invalid JSON: Missing keys {missing_keys}.")
            return False

    return True