#!/usr/bin/env python3 """ Example showing JSON conversion to SelectItem with custom key mappings. Demonstrates how to load JSON data and convert it to SelectItem instances with configurable field mappings. """ import json import os import sys sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src')) from selectui import SelectItem, SelectUI def load_json_as_selectitems(json_path, title_key, subtitle_key=None, info_key=None): """Load JSON file and convert to SelectItem instances.""" with open(json_path, 'r') as f: data = json.load(f) if not isinstance(data, list): data = [data] items = [ SelectItem.from_dict(item, title_key, subtitle_key, info_key) for item in data ] return items def example_custom_json(): """Load JSON with non-standard field names.""" print("Loading JSON with custom field mappings...\n", file=sys.stderr) # Create sample JSON data sample_data = [ { "product_name": "Laptop", "description": "High-performance laptop", "price": "$1299", "stock": 45, "category": "Electronics" }, { "product_name": "Mouse", "description": "Wireless optical mouse", "price": "$29", "stock": 200, "category": "Accessories" }, { "product_name": "Keyboard", "description": "Mechanical gaming keyboard", "price": "$89", "stock": 120, "category": "Accessories" }, ] # Convert to SelectItem with custom mappings items = [ SelectItem.from_dict( item, title_key="product_name", subtitle_key="description", info_key="price" ) for item in sample_data ] print("Converted items:", file=sys.stderr) for item in items: print(f" • {item.title} - {item.subtitle} [{item.info}]", file=sys.stderr) print(f" Category: {item.data.get('category')}, Stock: {item.data.get('stock')}", file=sys.stderr) print("\nSelect a product:\n", file=sys.stderr) app = SelectUI(items=items, oneshot=True) app.run() if app.selected_item: print("\nSelected product details:", file=sys.stderr) print(f" Name: {app.selected_item.get('product_name')}", file=sys.stderr) print(f" Price: {app.selected_item.get('price')}", file=sys.stderr) print(f" Stock: {app.selected_item.get('stock')}", file=sys.stderr) print(f" Category: {app.selected_item.get('category')}", file=sys.stderr) return app.selected_item def example_github_style_json(): """Simulate GitHub API response format.""" print("GitHub-style API response\n", file=sys.stderr) github_repos = [ { "name": "awesome-python", "full_name": "vinta/awesome-python", "description": "A curated list of awesome Python frameworks", "stargazers_count": 185000, "language": "Python", "html_url": "https://github.com/vinta/awesome-python" }, { "name": "flask", "full_name": "pallets/flask", "description": "The Python micro framework for building web applications", "stargazers_count": 66000, "language": "Python", "html_url": "https://github.com/pallets/flask" }, { "name": "django", "full_name": "django/django", "description": "The Web framework for perfectionists with deadlines", "stargazers_count": 78000, "language": "Python", "html_url": "https://github.com/django/django" }, ] items = [ SelectItem.from_dict( repo, title_key="full_name", subtitle_key="description", info_key="stargazers_count" ) for repo in github_repos ] app = SelectUI(items=items, oneshot=True) app.run() if app.selected_item: print(f"\nRepository URL: {app.selected_item.get('html_url')}", file=sys.stderr) print(f"Language: {app.selected_item.get('language')}", file=sys.stderr) return app.selected_item def example_api_response(): """Generic API response with nested data.""" print("API response with custom structure\n", file=sys.stderr) api_data = { "status": "success", "results": [ { "id": 101, "username": "alice", "email": "alice@example.com", "role": "admin", "last_login": "2024-01-15" }, { "id": 102, "username": "bob", "email": "bob@example.com", "role": "user", "last_login": "2024-01-14" }, { "id": 103, "username": "charlie", "email": "charlie@example.com", "role": "moderator", "last_login": "2024-01-13" }, ] } items = [ SelectItem.from_dict( user, title_key="username", subtitle_key="email", info_key="role" ) for user in api_data["results"] ] app = SelectUI(items=items, oneshot=True) app.run() if app.selected_item: print(f"\nUser ID: {app.selected_item.get('id')}", file=sys.stderr) print(f"Last login: {app.selected_item.get('last_login')}", file=sys.stderr) return app.selected_item def example_no_subtitle(): """JSON conversion with no subtitle (single-line display).""" print("Single-line display (no subtitle)\n", file=sys.stderr) files = [ {"filename": "config.json", "size": 1024, "modified": "2024-01-15"}, {"filename": "data.csv", "size": 4096, "modified": "2024-01-14"}, {"filename": "README.md", "size": 2048, "modified": "2024-01-13"}, ] items = [ SelectItem.from_dict( file, title_key="filename", subtitle_key=None, # No subtitle info_key="size" ) for file in files ] app = SelectUI(items=items, oneshot=True) app.run() return app.selected_item if __name__ == "__main__": examples = { "1": ("Custom product JSON", example_custom_json), "2": ("GitHub-style API", example_github_style_json), "3": ("Generic API response", example_api_response), "4": ("No subtitle (single-line)", example_no_subtitle), } if len(sys.argv) < 2: print("Usage: python json_conversion.py ", file=sys.stderr) print("\nAvailable examples:", file=sys.stderr) for num, (desc, _) in examples.items(): print(f" {num} - {desc}", file=sys.stderr) sys.exit(1) example_num = sys.argv[1] if example_num not in examples: print(f"Error: Example {example_num} not found", file=sys.stderr) sys.exit(1) desc, func = examples[example_num] result = func() if result: print(f"\n{'='*60}", file=sys.stderr) print("FULL RESULT:", file=sys.stderr) print(json.dumps(result, indent=2), file=sys.stderr)