-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.ltl
More file actions
262 lines (230 loc) · 7.2 KB
/
Copy pathjson.ltl
File metadata and controls
262 lines (230 loc) · 7.2 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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
-- stdlib/json.ltl
-- LATERALUS JSON Standard Library
-- Pure LATERALUS implementation of JSON encode/decode
-- Delegates to Python's json module for heavy lifting
module JSON
import "core"
import "strings"
import "collections"
-- ============================================================
-- Types
-- ============================================================
type JsonValue = int | float | str | bool | None | list[JsonValue] | dict[str, JsonValue]
struct JsonError {
message: str
position: int
}
-- ============================================================
-- Parsing
-- ============================================================
-- Parse a JSON string into a LATERALUS value
fn parse(text: str) -> any {
@python("
import json as _json
try:
_result = _json.loads(text)
except _json.JSONDecodeError as e:
raise RuntimeError(f'JSON parse error at {e.pos}: {e.msg}')
")
return @result
}
-- Parse JSON, returning None on error instead of raising
fn try_parse(text: str) -> any {
@python("
import json as _json
try:
_result = _json.loads(text)
except:
_result = None
")
return @result
}
-- ============================================================
-- Serialization
-- ============================================================
-- Convert a LATERALUS value to a compact JSON string
fn stringify(value: any) -> str {
@python("
import json as _json
_result = _json.dumps(value, separators=(',', ':'), default=str)
")
return @result
}
-- Convert to pretty-printed JSON
fn pretty(value: any, indent: int = 2) -> str {
@python("
import json as _json
_result = _json.dumps(value, indent=indent, default=str)
")
return @result
}
-- ============================================================
-- Path access
-- ============================================================
-- Access a nested value by dot-notation path
-- Example: get_path(obj, "user.address.city") -> "NYC"
fn get_path(obj: any, path: str) -> any {
let parts = strings.split(path, ".")
let current = obj
for part in parts {
if current == None {
return None
}
if @type(current) == "dict" {
current = current[part] if part in current else None
} else {
return None
}
}
return current
}
-- Set a value at a nested path, returning a new dict
fn set_path(obj: any, path: str, value: any) -> any {
let parts = strings.split(path, ".")
if len(parts) == 1 {
return {**obj, parts[0]: value}
}
let head = parts[0]
let rest = strings.join(parts[1:], ".")
let nested = obj[head] if head in obj else {}
return {**obj, head: set_path(nested, rest, value)}
}
-- Delete a key at a nested path
fn delete_path(obj: any, path: str) -> any {
let parts = strings.split(path, ".")
if len(parts) == 1 {
return {k: v for k, v in obj.items() if k != parts[0]}
}
let head = parts[0]
let rest = strings.join(parts[1:], ".")
return {**obj, head: delete_path(obj[head], rest)}
}
-- ============================================================
-- Transformation
-- ============================================================
-- Flatten a nested JSON object to a flat dict with dot-notation keys
fn flatten(obj: any, prefix: str = "") -> dict {
let result = {}
for key, value in obj.items() {
let full_key = if prefix == "" { key } else { prefix + "." + key }
if @type(value) == "dict" {
let nested = flatten(value, full_key)
result = {**result, **nested}
} else {
result[full_key] = value
}
}
return result
}
-- Unflatten a flat dot-notation dict back to nested structure
fn unflatten(flat: dict) -> dict {
let result = {}
for key, value in flat.items() {
result = set_path(result, key, value)
}
return result
}
-- Deep merge two JSON objects (second wins on conflict)
fn merge(base: any, overlay: any) -> any {
if @type(base) != "dict" or @type(overlay) != "dict" {
return overlay
}
let result = {**base}
for key, value in overlay.items() {
if key in result and @type(result[key]) == "dict" and @type(value) == "dict" {
result[key] = merge(result[key], value)
} else {
result[key] = value
}
}
return result
}
-- ============================================================
-- Schema / Validation
-- ============================================================
-- Validate a JSON value against a simple schema dict
-- Schema: {"field": "type", "field2": {"nested": "type"}, "list_field": ["type"]}
fn validate_schema(value: any, schema: any) -> list[str] {
let errors = []
if @type(schema) == "dict" and @type(value) == "dict" {
for key, expected_type in schema.items() {
if key not in value {
errors = errors + ["Missing required key: " + key]
continue
}
let sub_errors = validate_schema(value[key], expected_type)
errors = errors + sub_errors
} else if @type(schema) == "str" {
let actual = @type(value).__name__
if schema == "any" {
-- any type is always valid
} else if schema == "number" {
if actual not in ["int", "float"] {
errors = errors + ["Expected number, got " + actual]
}
} else if actual != schema {
errors = errors + ["Expected " + schema + ", got " + actual]
}
}
return errors
}
-- ============================================================
-- Utility
-- ============================================================
-- Count keys at all levels of a nested JSON object
fn count_keys(obj: any) -> int {
if @type(obj) != "dict" {
return 0
}
let total = len(obj)
for value in obj.values() {
total = total + count_keys(value)
}
return total
}
-- Extract all values at a given key from nested structures
fn pluck_deep(obj: any, key: str) -> list {
let results = []
if @type(obj) == "dict" {
if key in obj {
results = results + [obj[key]]
}
for value in obj.values() {
results = results + pluck_deep(value, key)
}
} else if @type(obj) == "list" {
for item in obj {
results = results + pluck_deep(item, key)
}
}
return results
}
-- ============================================================
-- Pipeline helpers
-- ============================================================
-- Parse then apply a pipeline function
fn parse_and(text: str, transform: fn) -> any {
return text |> parse |> transform
}
-- Load a JSON file
fn load_file(path: str) -> any {
@python("
import json as _json, pathlib as _pl
_p = _pl.Path(path)
if not _p.exists():
raise FileNotFoundError(f'JSON file not found: {path}')
with open(_p, 'r', encoding='utf-8') as _f:
_result = _json.load(_f)
")
return @result
}
-- Save a value to a JSON file
fn save_file(path: str, value: any, indent: int = 2) -> None {
@python("
import json as _json, pathlib as _pl
_p = _pl.Path(path)
_p.parent.mkdir(parents=True, exist_ok=True)
with open(_p, 'w', encoding='utf-8') as _f:
_json.dump(value, _f, indent=indent, default=str)
")
}