Metadata-Version: 2.5
Name: jsontron
Version: 0.3.0
Summary: Schematron-style business rules for JSON Schema (jsonschema), with jq expressions.
Project-URL: Homepage, https://github.com/devlooped/jsontron
Project-URL: Specification, https://github.com/devlooped/jsontron/blob/main/spec/jsontron.md
Author: Daniel Cazzulino and Contributors
License-Expression: MIT
Keywords: jq,jqlite,json-schema,jsonschema,rules,schematron,validation
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: attrs>=22.2
Requires-Dist: devlooped-jqlite>=1.0.0
Requires-Dist: jsonschema>=4.18
Provides-Extra: test
Requires-Dist: pytest>=8; extra == 'test'
Requires-Dist: ruff>=0.6; extra == 'test'
Description-Content-Type: text/markdown

# Jsontron for Python

Schematron-style business rules for JSON Schema, with [jq](https://jqlang.org) expressions:
the `rules`, `assert`, `report` and `let` keywords of the
[Jsontron specification](https://github.com/devlooped/jsontron/blob/main/spec/jsontron.md)
(version 0.2) for [jsonschema](https://pypi.org/project/jsonschema/) (draft 2020-12),
evaluated in-process by [devlooped-jqlite](https://pypi.org/project/devlooped-jqlite/)
(pure Python, no native extensions).

- Structural validation stays with JSON Schema.
- Cross-cutting rules stay in the schema, next to the data they describe.
- jq expressions are checked when the schema is checked, and compiled once.

## Quick start

```python
from jsontron import JsontronValidator

schema = {
    "type": "object",
    "required": ["orders", "policy", "approvedCustomers"],
    "rules": [
        {
            "context": ".orders[] | select(.total > 1000)",
            "asserts": [
                {
                    "test": ".discount >= ($root.policy.minHighValueDiscount // 0.1)",
                    "message": "High-value order \\(.id) discount \\(.discount) is below policy",
                },
                {
                    "test": ".customer.id | IN($root.approvedCustomers[])",
                    "message": "Customer \\(.customer.id) is not on the approved list",
                },
            ],
        }
    ],
}

document = {
    "policy": {"minHighValueDiscount": 0.15},
    "approvedCustomers": ["acme", "globex"],
    "orders": [
        {"id": "O-1001", "total": 2500, "discount": 0.05, "customer": {"id": "initech"}},
        {"id": "O-1002", "total": 80, "discount": 0, "customer": {"id": "unknown"}},
    ],
}

JsontronValidator.check_schema(schema)  # shape and every jq expression
validator = JsontronValidator(schema)

# O-1001 fails both asserts (discount + customer).
# O-1002 is ignored by the rule (total <= 1000).
for error in validator.iter_errors(document):
    print(error.message)
# High-value order O-1001 discount 0.05 is below policy
# Customer initech is not on the approved list

print(validator.is_valid(document))  # False
```

`JsontronValidator` is `jsonschema.Draft202012Validator` with the four keywords, and is used
like any jsonschema validator class: `iter_errors`, `validate`, `is_valid`, `check_schema`, and
`jsonschema.validate(document, schema, cls=JsontronValidator)`.

`jsontron.extend(validator_class)` adds the keywords to another validator class. To combine
them with keywords of your own, extend last:
`jsontron.extend(validators.extend(Draft202012Validator, {...}))`. A class made with
`validators.extend(JsontronValidator, ...)` loses what tracks the document for `$root`.

## Behaviour

- Each failed assert or report is one `ValidationError` whose message is the failure text
  (with its `[rule-id][item-id][flag=...]` prefix), at the location of the instance the schema
  object applies to. Its `validator` is the keyword that owns the rule set: `rules`, else
  `assert`, else `report`.
- A jq runtime error in a `let`, `context` or `test` is one `ValidationError` for the rule set.
- `check_schema` rejects invalid keyword values and invalid jq in any expression. A schema used
  without `check_schema` raises the same `SchemaError` when its invalid schema object is first
  applied.
- `$root` is the whole document, also under `properties`, `items`, `$ref` and applicators.
- A schema object is compiled once, on first use: changing it in place afterwards has no effect.

## Performance

Each schema object with a rule set compiles to one `jqlite` expression on first use (cached),
and runs it once per instance it applies to. Every run converts its input to `jqlite` values:
the instance, and the whole document when an expression reads `$root`. For large arrays, prefer
a rule at the parent with a `context` that selects the items over a rule set under `items` that
reads `$root`, so the document is converted once rather than per item.
