-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathexamples.py
More file actions
99 lines (88 loc) · 2.48 KB
/
examples.py
File metadata and controls
99 lines (88 loc) · 2.48 KB
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
"""Examples demonstrating python-toon usage."""
from toon import encode
# Example 1: Simple object
print("=" * 60)
print("Example 1: Simple Object")
print("=" * 60)
data = {"name": "Alice", "age": 30, "city": "New York"}
print("Input:", data)
print("\nTOON Output:")
print(encode(data))
# Example 2: Tabular array
print("\n" + "=" * 60)
print("Example 2: Tabular Array (Uniform Objects)")
print("=" * 60)
users = [
{"id": 1, "name": "Alice", "age": 30},
{"id": 2, "name": "Bob", "age": 25},
{"id": 3, "name": "Charlie", "age": 35},
]
print("Input:", users)
print("\nTOON Output:")
print(encode(users))
# Example 3: Complex nested structure
print("\n" + "=" * 60)
print("Example 3: Complex Nested Structure")
print("=" * 60)
data = {
"metadata": {"version": 1, "author": "test"},
"items": [
{"id": 1, "name": "Item1", "price": 9.99},
{"id": 2, "name": "Item2", "price": 19.99},
],
"tags": ["alpha", "beta", "gamma"],
}
print("Input:", data)
print("\nTOON Output:")
print(encode(data))
# Example 4: Different delimiters
print("\n" + "=" * 60)
print("Example 4: Different Delimiters")
print("=" * 60)
arr = [1, 2, 3, 4, 5]
print("Input:", arr)
print("\nComma (default):")
print(encode(arr))
print("\nTab delimiter:")
print(encode(arr, {"delimiter": "\t"}))
print("\nPipe delimiter:")
print(encode(arr, {"delimiter": "|"}))
# Example 5: Length markers
print("\n" + "=" * 60)
print("Example 5: Length Markers")
print("=" * 60)
users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
]
print("Input:", users)
print("\nWith length marker:")
print(encode(users, {"length_marker": True}))
# Example 6: Primitive arrays
print("\n" + "=" * 60)
print("Example 6: Primitive Arrays")
print("=" * 60)
print("Numbers:", encode([1, 2, 3, 4, 5]))
print("Strings:", encode(["apple", "banana", "cherry"]))
print("Mixed:", encode([1, "two", True, None]))
# Example 7: Token comparison
print("\n" + "=" * 60)
print("Example 7: Token Efficiency Demo")
print("=" * 60)
import json
data = {
"users": [
{"id": 1, "name": "Alice", "age": 30, "active": True},
{"id": 2, "name": "Bob", "age": 25, "active": True},
{"id": 3, "name": "Charlie", "age": 35, "active": False},
]
}
json_str = json.dumps(data)
toon_str = encode(data)
print(f"JSON length: {len(json_str)} characters")
print(f"TOON length: {len(toon_str)} characters")
print(f"Reduction: {100 * (1 - len(toon_str) / len(json_str)):.1f}%")
print("\nJSON:")
print(json_str)
print("\nTOON:")
print(toon_str)