Metadata-Version: 2.3
Name: JSLT
Version: 2.2.1
Summary: JSON transformation/templating engine
Keywords: json,engine,templating,transformation,jslt
Author: Daniel Rexin
Author-email: Daniel Rexin <daniel@medinion.de>
License: MIT License
         
         Copyright (c) 2026 Daniel Rexin
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
         in the Software without restriction, including without limitation the rights
         to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
         copies of the Software, and to permit persons to whom the Software is
         furnished to do so, subject to the following conditions:
         
         The above copyright notice and this permission notice shall be included in all
         copies or substantial portions of the Software.
         
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
         AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
         SOFTWARE.
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: License :: OSI Approved :: MIT License
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Dist: jmespath>=1.1.0
Requires-Dist: simpleeval>=1.0.7
Requires-Python: >=3.12.3
Project-URL: Homepage, https://github.com/danniedarko/jslt
Project-URL: Issues, https://github.com/danniedarko/jslt/issues
Project-URL: Repository, https://github.com/danniedarko/jslt
Description-Content-Type: text/markdown

# JSLT

**JSLT** is a JSON templating and transformation engine. It enables developers to declaratively map, filter, and reshape JSON data using pure JSON templates, powered by JMESPath for data extraction and a safe, stack-based execution model.

---

## 📦 Installation

```bash
pip install jslt
```

---

## 🚀 Quick Start

```python
import json
from jslt import JSLT

data = {
    "users": [
        {"name": "Alice", "age": 25, "score": 88.5},
        {"name": "Bob", "age": 17, "score": 92.0}
    ],
    "threshold": 18
}

template = {
    # Extract only adult users
    "adults": {
      "jsl:each": {
        "path": "users",
        "template": {
          "jsl:if": {
            "test": "age >= root().threshold",
            "then": {
              "name": {
                "jsl:path": "name"
              }
            }
          }
        }
      }
    },
    
    # Extract only adult users using jmespath
    "adults_jpath": {
      "jsl:var": {
        "name": "threshold",
        "path": "threshold"
      },
      "jsl:each": {
        "path": "users[?age>var('threshold')]",
        "template": {
          "name": {
            "jsl:path": "name"
          }
        }
      }
    },
    
    # Find names with score > 90
    "top_scorers": {"jsl:path": "users[?score>`90`].name"},
    
    # Calculate average score
    "avg_score": {"jsl:eval": "round(sum(users['*'].score) / count(users), 2)"},
    
    # Calculate average score using jmespath
    "avg_score_jpath": {"jsl:path": "avg(users[*].score)"}
}

jslt = JSLT(template)
result = jslt.transform(data)
print(json.dumps(result, indent=2))
```

**Output:**
```json
{
  "adults": [
    {
      "name": "Alice"
    }
  ],
  "adults_jpath": [
    {
      "name": "Alice"
    }
  ],
  "top_scorers": [
    "Bob"
  ],
  "avg_score": 90.25,
  "avg_score_jpath": 90.25
}
```

---

## 🔑 Core Features

- **JMESPath Integration:** Leverage full JMESPath syntax for powerful data extraction and filtering.
- **Custom DSL Functions:** Transform data using internal functions (`jsl:var`, `jsl:if`, `jsl:each`, `jsl:keep`, `jsl:eval`, `jsl:path`).
- **Stack-Based Iteration:** Uses an iterative stack engine to process templates, completely avoiding Python recursion limits.
- **Safe Expression Evaluation:** Math and logic expressions are evaluated securely via `simple_eval()`, preventing arbitrary code execution.

---

## 📝 Template DSL & Syntax

Templates are standard JSON objects. Each key defines an output field, and its value contains transformation instructions.

### 🔹 `JSL` Functions
All operations are prefixed with `jsl:` (namespace).
Object keys are passed to the function as named parameters. If the value is an array, the values are used as positional parameters.
The engine provides the following functions:
| Function | Description |
|----------|-------------|
| `jsl:var` | Store intermediate values for reuse |
| `jsl:if` | Conditional branching (`[test, then, other]`) |
| `jsl:each` | Iterate over arrays and apply child templates (`[path, template]`) |
| `jsl:keep` | Instructs the engine to keep this object, even if it resolves to None |
| `jsl:eval` | Evaluate arithmetic/logic expressions |
| `jsl:path` | Resolve a JMESPath |

---

## 🧭 JMESPath custom functions

Custom functions are injected into JMESPath to provide additional functionality:

- **Context Helpers:** 
  - `root()` → References the root node
  - `parent()` → Move up the data tree
  - `current()` → Reference the active node
  - `var()` → Gives access to previously defined variables 
- **Math:** 
  - `multiply()` → Multiply all values
- **Text**
  - `strip()` → Remove whitespace from string

---

## 𝑓 Developing custom DSL functions

To integrate custom functions you simply have to create a class inheriting from `jslt.engine.functions.Functions`
Each function defined within the class using the following naming convention will be registered as a custom function:
`_{namespace}_{function_name}`
`namespace` may contain only lowercase chars
`function_name` may only contain lowercase chars and underscores

The first parameter passed to each function will be the execution context of type `JSLT.Context`
The following parameters may be named parameters where each parameter will correspond to the value of the respective object key if the item is an object.
If the item is a list, each list item will be passed as a positional parameter.
A single value will be passed to the function as a positional parameter.

Within the template DSL you may call your custom functions using object keys in the format `{namespace}:{function_name}`

### Example

**Function code**
```python
from jslt.engine.functions import Functions
from jslt.engine.transform import JSLT


class CustomFunctions(Functions):
    def _custom_decorate_string(ctx: JSLT.Context, value: str):
        return f"### {value} ###"
```

**Template**
```json
{
    "root": {
        "my_value": "some value",
        "custom_value": {
            "custom:decorate_string": "custom value"
        }
    }
}
```

**Output***
```json
{
    "root": {
        "my_value": "some value",
        "custom_value": "### custom value ###"
    }
}
```
---

## 📜 License

This project is licensed under the MIT License. See `LICENSE` for details.
