jsonatapy 2.2.17__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jsonatapy/__init__.py +575 -0
- jsonatapy/__main__.py +46 -0
- jsonatapy/_cli/__init__.py +1 -0
- jsonatapy/_cli/bindings.py +51 -0
- jsonatapy/_cli/error_format.py +25 -0
- jsonatapy/_cli/mcp_server.py +192 -0
- jsonatapy/_cli/resolve.py +85 -0
- jsonatapy/_cli/run.py +204 -0
- jsonatapy/_jsonatapy.cp315-win_amd64.pyd +0 -0
- jsonatapy/py.typed +0 -0
- jsonatapy-2.2.17.dist-info/METADATA +323 -0
- jsonatapy-2.2.17.dist-info/RECORD +16 -0
- jsonatapy-2.2.17.dist-info/WHEEL +4 -0
- jsonatapy-2.2.17.dist-info/entry_points.txt +2 -0
- jsonatapy-2.2.17.dist-info/licenses/LICENSE +21 -0
- jsonatapy-2.2.17.dist-info/sboms/jsonata-core.cyclonedx.json +2243 -0
jsonatapy/__init__.py
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
"""
|
|
2
|
+
jsonatapy - High-performance Python implementation of JSONata
|
|
3
|
+
|
|
4
|
+
JSONata is a lightweight query and transformation language for JSON data.
|
|
5
|
+
|
|
6
|
+
Example:
|
|
7
|
+
>>> import jsonatapy
|
|
8
|
+
>>> data = {"name": "World"}
|
|
9
|
+
>>> result = jsonatapy.evaluate('"Hello, " & name', data)
|
|
10
|
+
>>> print(result)
|
|
11
|
+
"Hello, World"
|
|
12
|
+
|
|
13
|
+
>>> # Compile once, evaluate many times
|
|
14
|
+
>>> expr = jsonatapy.compile("orders[price > 100].product")
|
|
15
|
+
>>> result = expr.evaluate(data)
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import json as _json
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from ._jsonatapy import (
|
|
23
|
+
JsonataData as _JsonataData,
|
|
24
|
+
)
|
|
25
|
+
from ._jsonatapy import (
|
|
26
|
+
JsonataExpression as _JsonataExpression,
|
|
27
|
+
)
|
|
28
|
+
from ._jsonatapy import (
|
|
29
|
+
__jsonata_version__,
|
|
30
|
+
__version__,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
# Private test hooks (not public API): runtime toggle forcing the
|
|
34
|
+
# tree-walking evaluator; seeded from JSONATAPY_FORCE_TREE_WALKER at import.
|
|
35
|
+
from ._jsonatapy import _get_force_tree_walker as _get_force_tree_walker
|
|
36
|
+
from ._jsonatapy import _set_force_tree_walker as _set_force_tree_walker
|
|
37
|
+
from ._jsonatapy import (
|
|
38
|
+
compile as _compile,
|
|
39
|
+
)
|
|
40
|
+
from ._jsonatapy import (
|
|
41
|
+
evaluate as _evaluate,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"JsonataData",
|
|
46
|
+
"JsonataExpression",
|
|
47
|
+
"__jsonata_version__",
|
|
48
|
+
"__version__",
|
|
49
|
+
"compile",
|
|
50
|
+
"evaluate",
|
|
51
|
+
"json_dumps",
|
|
52
|
+
"json_loads",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
# Use orjson when available for faster JSON serialization (3x faster than stdlib).
|
|
56
|
+
# These are exposed for users who want to use the evaluate_json() path with
|
|
57
|
+
# optimal serialization performance.
|
|
58
|
+
try:
|
|
59
|
+
import orjson as _orjson
|
|
60
|
+
|
|
61
|
+
def json_dumps(obj: Any) -> str:
|
|
62
|
+
"""Serialize to JSON string, using orjson if available."""
|
|
63
|
+
return _orjson.dumps(obj).decode("utf-8")
|
|
64
|
+
|
|
65
|
+
def json_loads(s: str | bytes) -> Any:
|
|
66
|
+
"""Deserialize JSON string, using orjson if available."""
|
|
67
|
+
return _orjson.loads(s)
|
|
68
|
+
|
|
69
|
+
except ImportError:
|
|
70
|
+
|
|
71
|
+
def json_dumps(obj: Any) -> str:
|
|
72
|
+
"""Serialize to JSON string, using stdlib json."""
|
|
73
|
+
return _json.dumps(obj)
|
|
74
|
+
|
|
75
|
+
def json_loads(s: str | bytes) -> Any:
|
|
76
|
+
"""Deserialize JSON string, using stdlib json."""
|
|
77
|
+
return _json.loads(s)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class JsonataData:
|
|
81
|
+
"""
|
|
82
|
+
Pre-converted data handle for efficient repeated evaluation.
|
|
83
|
+
|
|
84
|
+
Convert Python data to an internal representation once, then reuse it
|
|
85
|
+
across multiple evaluations to avoid repeated Python-to-Rust conversion overhead.
|
|
86
|
+
|
|
87
|
+
Example:
|
|
88
|
+
>>> data = JsonataData({"orders": [{"price": 150}, {"price": 50}]})
|
|
89
|
+
>>> expr = compile("orders[price > 100]")
|
|
90
|
+
>>> result = expr.evaluate_with_data(data)
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
def __init__(self, data: Any) -> None:
|
|
94
|
+
"""
|
|
95
|
+
Create a JsonataData handle from a Python object.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
data: The data to pre-convert (typically a dict or list)
|
|
99
|
+
"""
|
|
100
|
+
self._data = _JsonataData(data)
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
def from_json(cls, json_str: str) -> "JsonataData":
|
|
104
|
+
"""
|
|
105
|
+
Create a JsonataData handle from a JSON string (fastest path).
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
json_str: Input data as a JSON string
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
A JsonataData handle
|
|
112
|
+
|
|
113
|
+
Raises:
|
|
114
|
+
ValueError: If the JSON string is invalid
|
|
115
|
+
"""
|
|
116
|
+
obj = cls.__new__(cls)
|
|
117
|
+
obj._data = _JsonataData.from_json(json_str)
|
|
118
|
+
return obj
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class JsonataExpression:
|
|
122
|
+
"""
|
|
123
|
+
A compiled JSONata expression.
|
|
124
|
+
|
|
125
|
+
This class wraps the Rust-implemented expression compiler and evaluator.
|
|
126
|
+
|
|
127
|
+
Attributes:
|
|
128
|
+
_expr: The underlying Rust expression object
|
|
129
|
+
|
|
130
|
+
Example:
|
|
131
|
+
>>> expr = JsonataExpression.compile("$.name")
|
|
132
|
+
>>> result = expr.evaluate({"name": "Alice"})
|
|
133
|
+
>>> print(result)
|
|
134
|
+
"Alice"
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
def __init__(self, expr: _JsonataExpression) -> None:
|
|
138
|
+
"""
|
|
139
|
+
Initialize a JsonataExpression.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
expr: The compiled Rust expression object
|
|
143
|
+
|
|
144
|
+
Note:
|
|
145
|
+
Users should typically use the `compile()` function instead
|
|
146
|
+
of instantiating this class directly.
|
|
147
|
+
"""
|
|
148
|
+
self._expr = expr
|
|
149
|
+
|
|
150
|
+
def evaluate(
|
|
151
|
+
self,
|
|
152
|
+
data: Any,
|
|
153
|
+
bindings: dict[str, Any] | None = None,
|
|
154
|
+
*,
|
|
155
|
+
timeout: int | None = None,
|
|
156
|
+
max_stack_depth: int | None = None,
|
|
157
|
+
max_sequence_length: int | None = None,
|
|
158
|
+
) -> Any:
|
|
159
|
+
"""
|
|
160
|
+
Evaluate this expression against data.
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
data: The data to query/transform (typically a dict or list)
|
|
164
|
+
bindings: Optional additional variable bindings
|
|
165
|
+
timeout: Maximum evaluation time in milliseconds (raises ValueError
|
|
166
|
+
with a D1012 code on timeout). Overrides any default set via
|
|
167
|
+
`compile(timeout=...)` for this call only.
|
|
168
|
+
max_stack_depth: Maximum recursion stack depth (raises ValueError
|
|
169
|
+
with a D1011 code when exceeded). Overrides any compile-time default.
|
|
170
|
+
max_sequence_length: Maximum length of a query-result sequence
|
|
171
|
+
(map/filter/wildcard/descendants/etc; raises ValueError with a
|
|
172
|
+
D2015 code when exceeded). Overrides any compile-time default.
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
The result of evaluating the expression
|
|
176
|
+
|
|
177
|
+
Raises:
|
|
178
|
+
ValueError: If evaluation fails, or a guardrail is exceeded
|
|
179
|
+
|
|
180
|
+
Example:
|
|
181
|
+
>>> expr = compile("orders[price > 100]")
|
|
182
|
+
>>> data = {"orders": [{"price": 150}, {"price": 50}]}
|
|
183
|
+
>>> result = expr.evaluate(data)
|
|
184
|
+
>>> print(len(result))
|
|
185
|
+
1
|
|
186
|
+
"""
|
|
187
|
+
return self._expr.evaluate(data, bindings, timeout, max_stack_depth, max_sequence_length)
|
|
188
|
+
|
|
189
|
+
def register(self, name: str, func: Callable[..., Any]) -> "JsonataExpression":
|
|
190
|
+
"""
|
|
191
|
+
Register a Python function callable from the expression as ``$name(...)``.
|
|
192
|
+
|
|
193
|
+
The function receives the (already-evaluated) arguments as positional
|
|
194
|
+
Python values and must return a JSON-compatible value **synchronously**.
|
|
195
|
+
This is the equivalent of jsonata-js's ``registerFunction`` — use it to
|
|
196
|
+
expose enrichment/lookup, formatting, or scoring logic to an expression.
|
|
197
|
+
|
|
198
|
+
Host functions resolve after the expression's own bindings/lambdas and
|
|
199
|
+
before built-ins. A name that collides with a built-in is rejected; use
|
|
200
|
+
:meth:`register_override` to replace a built-in deliberately.
|
|
201
|
+
|
|
202
|
+
Note:
|
|
203
|
+
The evaluator is synchronous, so an ``async def`` (which returns a
|
|
204
|
+
coroutine) is rejected at call time. For async I/O, await it outside
|
|
205
|
+
jsonata and pass the result in via ``bindings``.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
name: The function name, called as ``$name(...)`` in the expression.
|
|
209
|
+
func: A callable ``(*args) -> JSON-compatible value``.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
self, to allow chaining.
|
|
213
|
+
|
|
214
|
+
Raises:
|
|
215
|
+
TypeError: If ``func`` is not callable.
|
|
216
|
+
ValueError: If ``name`` collides with a built-in function.
|
|
217
|
+
|
|
218
|
+
Example:
|
|
219
|
+
>>> expr = compile("$greet(name)")
|
|
220
|
+
>>> expr.register("greet", lambda n: f"hello {n}")
|
|
221
|
+
>>> expr.evaluate({"name": "Ada"})
|
|
222
|
+
'hello Ada'
|
|
223
|
+
"""
|
|
224
|
+
self._expr.register(name, func)
|
|
225
|
+
return self
|
|
226
|
+
|
|
227
|
+
def register_override(self, name: str, func: Callable[..., Any]) -> "JsonataExpression":
|
|
228
|
+
"""
|
|
229
|
+
Register a Python function that deliberately replaces a built-in.
|
|
230
|
+
|
|
231
|
+
The two legitimate uses are determinism injection for the impure
|
|
232
|
+
built-ins (``$now``, ``$millis``, ``$random``) — e.g. a frozen clock for
|
|
233
|
+
reproducible output — and sandboxing (disabling ``$eval``). Overriding a
|
|
234
|
+
built-in that participates in the compiled fast path is rejected.
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
name: The built-in name to replace (e.g. ``"now"``).
|
|
238
|
+
func: A callable ``(*args) -> JSON-compatible value``.
|
|
239
|
+
|
|
240
|
+
Returns:
|
|
241
|
+
self, to allow chaining.
|
|
242
|
+
|
|
243
|
+
Raises:
|
|
244
|
+
TypeError: If ``func`` is not callable.
|
|
245
|
+
ValueError: If the built-in cannot be safely overridden.
|
|
246
|
+
|
|
247
|
+
Example:
|
|
248
|
+
>>> expr = compile("$now()")
|
|
249
|
+
>>> expr.register_override("now", lambda: "2020-01-01T00:00:00.000Z")
|
|
250
|
+
>>> expr.evaluate(None)
|
|
251
|
+
'2020-01-01T00:00:00.000Z'
|
|
252
|
+
"""
|
|
253
|
+
self._expr.register_override(name, func)
|
|
254
|
+
return self
|
|
255
|
+
|
|
256
|
+
def evaluate_json(
|
|
257
|
+
self,
|
|
258
|
+
json_str: str,
|
|
259
|
+
bindings: dict[str, Any] | None = None,
|
|
260
|
+
*,
|
|
261
|
+
timeout: int | None = None,
|
|
262
|
+
max_stack_depth: int | None = None,
|
|
263
|
+
max_sequence_length: int | None = None,
|
|
264
|
+
) -> str:
|
|
265
|
+
"""
|
|
266
|
+
Evaluate this expression with JSON string input/output (faster for large data).
|
|
267
|
+
|
|
268
|
+
This method avoids Python↔Rust conversion overhead by accepting and returning
|
|
269
|
+
JSON strings directly. This is significantly faster for large datasets (10-50x speedup).
|
|
270
|
+
|
|
271
|
+
Args:
|
|
272
|
+
json_str: Input data as a JSON string
|
|
273
|
+
bindings: Optional additional variable bindings
|
|
274
|
+
timeout: Maximum evaluation time in milliseconds (raises ValueError
|
|
275
|
+
with a D1012 code on timeout). Overrides any default set via
|
|
276
|
+
`compile(timeout=...)` for this call only.
|
|
277
|
+
max_stack_depth: Maximum recursion stack depth (raises ValueError
|
|
278
|
+
with a D1011 code when exceeded). Overrides any compile-time default.
|
|
279
|
+
max_sequence_length: Maximum length of a query-result sequence
|
|
280
|
+
(map/filter/wildcard/descendants/etc; raises ValueError with a
|
|
281
|
+
D2015 code when exceeded). Overrides any compile-time default.
|
|
282
|
+
|
|
283
|
+
Returns:
|
|
284
|
+
The result as a JSON string
|
|
285
|
+
|
|
286
|
+
Raises:
|
|
287
|
+
ValueError: If JSON parsing or evaluation fails, or a guardrail is exceeded
|
|
288
|
+
|
|
289
|
+
Example:
|
|
290
|
+
>>> import json
|
|
291
|
+
>>> expr = compile("items[price > 100]")
|
|
292
|
+
>>> json_str = json.dumps({"items": [{"price": 150}, {"price": 50}]})
|
|
293
|
+
>>> result_str = expr.evaluate_json(json_str)
|
|
294
|
+
>>> result = json.loads(result_str)
|
|
295
|
+
>>> print(len(result))
|
|
296
|
+
1
|
|
297
|
+
|
|
298
|
+
Note:
|
|
299
|
+
For large datasets (1000+ items), this can be 10-50x faster than evaluate()
|
|
300
|
+
due to avoiding the Python↔Rust object conversion overhead.
|
|
301
|
+
"""
|
|
302
|
+
return self._expr.evaluate_json(
|
|
303
|
+
json_str, bindings, timeout, max_stack_depth, max_sequence_length
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
def evaluate_json_or_none(
|
|
307
|
+
self,
|
|
308
|
+
json_str: str | None,
|
|
309
|
+
bindings: dict[str, Any] | None = None,
|
|
310
|
+
*,
|
|
311
|
+
timeout: int | None = None,
|
|
312
|
+
max_stack_depth: int | None = None,
|
|
313
|
+
max_sequence_length: int | None = None,
|
|
314
|
+
) -> str | None:
|
|
315
|
+
"""
|
|
316
|
+
Evaluate with JSON string input, distinguishing Undefined from null.
|
|
317
|
+
|
|
318
|
+
Unlike evaluate_json(), which serializes both a JSONata Undefined
|
|
319
|
+
result and an explicit JSON null result to the same text "null",
|
|
320
|
+
this method returns None (the Python value) for Undefined and the
|
|
321
|
+
string "null" for an explicit null result.
|
|
322
|
+
|
|
323
|
+
Args:
|
|
324
|
+
json_str: Input data as a JSON string, or None for no input
|
|
325
|
+
document at all -- the top-level context (`$`) is then a
|
|
326
|
+
true JSONata Undefined, distinct from passing "null" (an
|
|
327
|
+
explicit JSON null context).
|
|
328
|
+
bindings: Optional additional variable bindings
|
|
329
|
+
timeout: Maximum evaluation time in milliseconds (raises ValueError
|
|
330
|
+
with a D1012 code on timeout). Overrides any default set via
|
|
331
|
+
`compile(timeout=...)` for this call only.
|
|
332
|
+
max_stack_depth: Maximum recursion stack depth (raises ValueError
|
|
333
|
+
with a D1011 code when exceeded). Overrides any compile-time default.
|
|
334
|
+
max_sequence_length: Maximum length of a query-result sequence
|
|
335
|
+
(map/filter/wildcard/descendants/etc; raises ValueError with a
|
|
336
|
+
D2015 code when exceeded). Overrides any compile-time default.
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
None if the result is JSONata Undefined, otherwise the result
|
|
340
|
+
as a JSON string (e.g. "null" for an explicit null result).
|
|
341
|
+
|
|
342
|
+
Raises:
|
|
343
|
+
ValueError: If JSON parsing or evaluation fails, or a guardrail is exceeded
|
|
344
|
+
|
|
345
|
+
Example:
|
|
346
|
+
>>> expr = compile("nonexistent")
|
|
347
|
+
>>> expr.evaluate_json_or_none('{"a": 1}') is None
|
|
348
|
+
True
|
|
349
|
+
>>> expr2 = compile("a")
|
|
350
|
+
>>> expr2.evaluate_json_or_none('{"a": null}')
|
|
351
|
+
'null'
|
|
352
|
+
"""
|
|
353
|
+
return self._expr.evaluate_json_or_none(
|
|
354
|
+
json_str, bindings, timeout, max_stack_depth, max_sequence_length
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
def evaluate_with_data(
|
|
358
|
+
self,
|
|
359
|
+
data: "JsonataData",
|
|
360
|
+
bindings: dict[str, Any] | None = None,
|
|
361
|
+
*,
|
|
362
|
+
timeout: int | None = None,
|
|
363
|
+
max_stack_depth: int | None = None,
|
|
364
|
+
max_sequence_length: int | None = None,
|
|
365
|
+
) -> Any:
|
|
366
|
+
"""
|
|
367
|
+
Evaluate with pre-converted data (fastest for repeated evaluation).
|
|
368
|
+
|
|
369
|
+
Args:
|
|
370
|
+
data: A JsonataData handle (pre-converted data)
|
|
371
|
+
bindings: Optional additional variable bindings
|
|
372
|
+
timeout: Maximum evaluation time in milliseconds (raises ValueError
|
|
373
|
+
with a D1012 code on timeout). Overrides any default set via
|
|
374
|
+
`compile(timeout=...)` for this call only.
|
|
375
|
+
max_stack_depth: Maximum recursion stack depth (raises ValueError
|
|
376
|
+
with a D1011 code when exceeded). Overrides any compile-time default.
|
|
377
|
+
max_sequence_length: Maximum length of a query-result sequence
|
|
378
|
+
(map/filter/wildcard/descendants/etc; raises ValueError with a
|
|
379
|
+
D2015 code when exceeded). Overrides any compile-time default.
|
|
380
|
+
|
|
381
|
+
Returns:
|
|
382
|
+
The result of evaluating the expression
|
|
383
|
+
|
|
384
|
+
Raises:
|
|
385
|
+
ValueError: If evaluation fails, or a guardrail is exceeded
|
|
386
|
+
|
|
387
|
+
Example:
|
|
388
|
+
>>> data = JsonataData({"orders": [{"price": 150}, {"price": 50}]})
|
|
389
|
+
>>> expr = compile("orders[price > 100]")
|
|
390
|
+
>>> result = expr.evaluate_with_data(data)
|
|
391
|
+
"""
|
|
392
|
+
return self._expr.evaluate_with_data(
|
|
393
|
+
data._data, bindings, timeout, max_stack_depth, max_sequence_length
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
def evaluate_data_to_json(
|
|
397
|
+
self,
|
|
398
|
+
data: "JsonataData",
|
|
399
|
+
bindings: dict[str, Any] | None = None,
|
|
400
|
+
*,
|
|
401
|
+
timeout: int | None = None,
|
|
402
|
+
max_stack_depth: int | None = None,
|
|
403
|
+
max_sequence_length: int | None = None,
|
|
404
|
+
) -> str:
|
|
405
|
+
"""
|
|
406
|
+
Evaluate with pre-converted data, return JSON string (zero-overhead output).
|
|
407
|
+
|
|
408
|
+
This is the fastest evaluation path: no Python-to-Rust conversion on input
|
|
409
|
+
(data is pre-converted), and no Rust-to-Python conversion on output (returns
|
|
410
|
+
a JSON string).
|
|
411
|
+
|
|
412
|
+
Args:
|
|
413
|
+
data: A JsonataData handle (pre-converted data)
|
|
414
|
+
bindings: Optional additional variable bindings
|
|
415
|
+
timeout: Maximum evaluation time in milliseconds (raises ValueError
|
|
416
|
+
with a D1012 code on timeout). Overrides any default set via
|
|
417
|
+
`compile(timeout=...)` for this call only.
|
|
418
|
+
max_stack_depth: Maximum recursion stack depth (raises ValueError
|
|
419
|
+
with a D1011 code when exceeded). Overrides any compile-time default.
|
|
420
|
+
max_sequence_length: Maximum length of a query-result sequence
|
|
421
|
+
(map/filter/wildcard/descendants/etc; raises ValueError with a
|
|
422
|
+
D2015 code when exceeded). Overrides any compile-time default.
|
|
423
|
+
|
|
424
|
+
Returns:
|
|
425
|
+
The result as a JSON string
|
|
426
|
+
|
|
427
|
+
Raises:
|
|
428
|
+
ValueError: If evaluation fails, or a guardrail is exceeded
|
|
429
|
+
|
|
430
|
+
Example:
|
|
431
|
+
>>> import json
|
|
432
|
+
>>> data = JsonataData.from_json('{"orders": [{"price": 150}, {"price": 50}]}')
|
|
433
|
+
>>> expr = compile("orders[price > 100]")
|
|
434
|
+
>>> result_str = expr.evaluate_data_to_json(data)
|
|
435
|
+
>>> result = json.loads(result_str)
|
|
436
|
+
"""
|
|
437
|
+
return self._expr.evaluate_data_to_json(
|
|
438
|
+
data._data, bindings, timeout, max_stack_depth, max_sequence_length
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
@classmethod
|
|
442
|
+
def compile(
|
|
443
|
+
cls,
|
|
444
|
+
expression: str,
|
|
445
|
+
*,
|
|
446
|
+
timeout: int | None = None,
|
|
447
|
+
max_stack_depth: int | None = None,
|
|
448
|
+
max_sequence_length: int | None = None,
|
|
449
|
+
) -> "JsonataExpression":
|
|
450
|
+
"""
|
|
451
|
+
Compile a JSONata expression.
|
|
452
|
+
|
|
453
|
+
This is an alternative constructor that compiles an expression string.
|
|
454
|
+
|
|
455
|
+
Args:
|
|
456
|
+
expression: A JSONata expression string
|
|
457
|
+
timeout: Default max evaluation time in milliseconds for all
|
|
458
|
+
evaluate*() calls on this expression (can be overridden per-call).
|
|
459
|
+
max_stack_depth: Default max recursion stack depth (can be overridden per-call).
|
|
460
|
+
max_sequence_length: Default max query-result sequence length
|
|
461
|
+
(can be overridden per-call).
|
|
462
|
+
|
|
463
|
+
Returns:
|
|
464
|
+
A compiled JsonataExpression
|
|
465
|
+
|
|
466
|
+
Raises:
|
|
467
|
+
ValueError: If the expression cannot be parsed
|
|
468
|
+
|
|
469
|
+
Example:
|
|
470
|
+
>>> expr = JsonataExpression.compile("$.name")
|
|
471
|
+
>>> expr = JsonataExpression.compile("$.name", timeout=5000)
|
|
472
|
+
"""
|
|
473
|
+
return cls(_compile(expression, timeout, max_stack_depth, max_sequence_length))
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def compile(
|
|
477
|
+
expression: str,
|
|
478
|
+
*,
|
|
479
|
+
timeout: int | None = None,
|
|
480
|
+
max_stack_depth: int | None = None,
|
|
481
|
+
max_sequence_length: int | None = None,
|
|
482
|
+
) -> JsonataExpression:
|
|
483
|
+
"""
|
|
484
|
+
Compile a JSONata expression into an executable form.
|
|
485
|
+
|
|
486
|
+
Args:
|
|
487
|
+
expression: A JSONata query/transformation expression string
|
|
488
|
+
timeout: Default max evaluation time in milliseconds for all
|
|
489
|
+
evaluate*() calls on this expression (can be overridden per-call).
|
|
490
|
+
max_stack_depth: Default max recursion stack depth (can be overridden per-call).
|
|
491
|
+
max_sequence_length: Default max query-result sequence length
|
|
492
|
+
(can be overridden per-call).
|
|
493
|
+
|
|
494
|
+
Returns:
|
|
495
|
+
A compiled JsonataExpression that can be evaluated multiple times
|
|
496
|
+
|
|
497
|
+
Raises:
|
|
498
|
+
ValueError: If the expression cannot be parsed
|
|
499
|
+
|
|
500
|
+
Example:
|
|
501
|
+
>>> expr = compile("orders[price > 100].product")
|
|
502
|
+
>>> result = expr.evaluate(data)
|
|
503
|
+
>>> expr = compile("$sum(items.price)", timeout=5000)
|
|
504
|
+
|
|
505
|
+
Note:
|
|
506
|
+
Compiling an expression once and evaluating it multiple times
|
|
507
|
+
is more efficient than calling `evaluate()` repeatedly with
|
|
508
|
+
the same expression string.
|
|
509
|
+
"""
|
|
510
|
+
try:
|
|
511
|
+
return JsonataExpression(
|
|
512
|
+
_compile(expression, timeout, max_stack_depth, max_sequence_length)
|
|
513
|
+
)
|
|
514
|
+
except UnicodeEncodeError as exc:
|
|
515
|
+
# A Python str may hold an unpaired surrogate; a Rust String may not,
|
|
516
|
+
# so such an expression cannot cross the boundary at all and PyO3
|
|
517
|
+
# raises a bare UnicodeEncodeError. Re-raise as ValueError so the
|
|
518
|
+
# library keeps one error type, and say why rather than leaking a
|
|
519
|
+
# codec message.
|
|
520
|
+
raise ValueError(
|
|
521
|
+
"Expression contains an unpaired surrogate and cannot be compiled: "
|
|
522
|
+
f"{exc.object[exc.start : exc.end]!r} at position {exc.start}"
|
|
523
|
+
) from exc
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def evaluate(
|
|
527
|
+
expression: str,
|
|
528
|
+
data: Any,
|
|
529
|
+
bindings: dict[str, Any] | None = None,
|
|
530
|
+
*,
|
|
531
|
+
timeout: int | None = None,
|
|
532
|
+
max_stack_depth: int | None = None,
|
|
533
|
+
max_sequence_length: int | None = None,
|
|
534
|
+
) -> Any:
|
|
535
|
+
"""
|
|
536
|
+
Compile and evaluate a JSONata expression in one step.
|
|
537
|
+
|
|
538
|
+
This is a convenience function for one-off evaluations.
|
|
539
|
+
For repeated evaluations, use `compile()` instead.
|
|
540
|
+
|
|
541
|
+
Args:
|
|
542
|
+
expression: A JSONata query/transformation expression string
|
|
543
|
+
data: The data to query/transform (typically a dict or list)
|
|
544
|
+
bindings: Optional additional variable bindings
|
|
545
|
+
timeout: Maximum evaluation time in milliseconds (raises ValueError
|
|
546
|
+
with a D1012 code on timeout).
|
|
547
|
+
max_stack_depth: Maximum recursion stack depth (raises ValueError
|
|
548
|
+
with a D1011 code when exceeded).
|
|
549
|
+
max_sequence_length: Maximum length of a query-result sequence
|
|
550
|
+
(raises ValueError with a D2015 code when exceeded).
|
|
551
|
+
|
|
552
|
+
Returns:
|
|
553
|
+
The result of evaluating the expression
|
|
554
|
+
|
|
555
|
+
Raises:
|
|
556
|
+
ValueError: If parsing or evaluation fails, or a guardrail is exceeded
|
|
557
|
+
|
|
558
|
+
Example:
|
|
559
|
+
>>> data = {"name": "alice"}
|
|
560
|
+
>>> result = evaluate("$uppercase(name)", data)
|
|
561
|
+
>>> print(result)
|
|
562
|
+
"ALICE"
|
|
563
|
+
|
|
564
|
+
>>> # With bindings
|
|
565
|
+
>>> result = evaluate("name & suffix", {"name": "Hello"}, {"suffix": "!"})
|
|
566
|
+
>>> print(result)
|
|
567
|
+
"Hello!"
|
|
568
|
+
|
|
569
|
+
>>> # With a timeout guardrail (protects against non-terminating expressions)
|
|
570
|
+
>>> evaluate("($inf := function(){$inf()}; $inf())", None, timeout=100)
|
|
571
|
+
Traceback (most recent call last):
|
|
572
|
+
...
|
|
573
|
+
ValueError: D1012: Evaluation timeout after 100 milliseconds. Check for infinite loop
|
|
574
|
+
"""
|
|
575
|
+
return _evaluate(expression, data, bindings, timeout, max_stack_depth, max_sequence_length)
|
jsonatapy/__main__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Console-script entry point for the `jsonatapy` CLI.
|
|
2
|
+
|
|
3
|
+
Dispatches to the MCP server subcommand (`jsonatapy mcp ...`) or evaluate
|
|
4
|
+
mode (everything else). See study/cli_spec.md for the full contract.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from ._cli.run import run
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _run_mcp(argv: list[str]) -> int:
|
|
16
|
+
parser = argparse.ArgumentParser(prog="jsonatapy mcp", description="Run the JSONata MCP server")
|
|
17
|
+
parser.add_argument("--http", action="store_true", help="Serve over HTTP instead of stdio")
|
|
18
|
+
parser.add_argument(
|
|
19
|
+
"--port", type=int, default=None, metavar="N", help="HTTP port (default 8000)"
|
|
20
|
+
)
|
|
21
|
+
args = parser.parse_args(argv)
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
from ._cli.mcp_server import serve
|
|
25
|
+
except ImportError:
|
|
26
|
+
print(
|
|
27
|
+
"error: the 'mcp' extra is not installed (it needs Python 3.11 or later). Run:\n"
|
|
28
|
+
' uvx --from "jsonatapy[mcp]" jsonatapy mcp\n'
|
|
29
|
+
"or: pip install jsonatapy[mcp]",
|
|
30
|
+
file=sys.stderr,
|
|
31
|
+
)
|
|
32
|
+
return 2
|
|
33
|
+
|
|
34
|
+
serve(args.http, args.port)
|
|
35
|
+
return 0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def main() -> int:
|
|
39
|
+
argv = sys.argv[1:]
|
|
40
|
+
if argv[:1] == ["mcp"]:
|
|
41
|
+
return _run_mcp(argv[1:])
|
|
42
|
+
return run(argv)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
sys.exit(main())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Internal CLI implementation for the `jsonatapy` console script. Not public API."""
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Parses --arg/--argjson CLI specs into a name -> value map for
|
|
2
|
+
evaluate_json_or_none() bindings."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class BindingError(Exception):
|
|
12
|
+
"""Raised when an --arg/--argjson spec is malformed."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _reject_constant(token: str) -> float:
|
|
16
|
+
raise ValueError(f"{token} is not valid JSON")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _finite_float(text: str) -> float:
|
|
20
|
+
value = float(text)
|
|
21
|
+
if not math.isfinite(value):
|
|
22
|
+
raise ValueError(f"{text} is not valid JSON")
|
|
23
|
+
return value
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def parse_bindings(arg: list[str], argjson: list[str]) -> dict[str, Any]:
|
|
27
|
+
"""Parses --arg NAME=VALUE (string) and --argjson NAME=JSON (parsed) specs
|
|
28
|
+
into a single name -> value dict. --argjson wins on name collision
|
|
29
|
+
(applied second, matching src/bin/jsonata/bindings.rs's iteration order)."""
|
|
30
|
+
bindings: dict[str, Any] = {}
|
|
31
|
+
for spec in arg:
|
|
32
|
+
name, value = _split_name_value(spec, "--arg")
|
|
33
|
+
bindings[name] = value
|
|
34
|
+
for spec in argjson:
|
|
35
|
+
name, value = _split_name_value(spec, "--argjson")
|
|
36
|
+
try:
|
|
37
|
+
bindings[name] = json.loads(
|
|
38
|
+
value, parse_constant=_reject_constant, parse_float=_finite_float
|
|
39
|
+
)
|
|
40
|
+
except ValueError as e:
|
|
41
|
+
raise BindingError(f"--argjson {name}: invalid JSON value: {e}") from e
|
|
42
|
+
return bindings
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _split_name_value(spec: str, flag: str) -> tuple[str, str]:
|
|
46
|
+
if "=" not in spec:
|
|
47
|
+
raise BindingError(f"{flag} expects NAME=VALUE, got: {spec}")
|
|
48
|
+
name, _, value = spec.partition("=")
|
|
49
|
+
if not name:
|
|
50
|
+
raise BindingError(f"{flag} expects NAME=VALUE, got: {spec}")
|
|
51
|
+
return name, value
|