aboutsummaryrefslogtreecommitdiffstats
path: root/examples/json_conversion.py
blob: 5e502fb547c38e0c98368c70ed4d57c9294a3861 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
#!/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 <example_number>", 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)