panzi-json-logic: JsonLogic and CertLogic Implementation
panzi-json-logic is a Pure Python 3 implementation of JsonLogic and CertLogic. It aims to closely emulate the behavior of the JavaScript JsonLogic specification, including specific operator semantics. The library facilitates sharing declarative rules (logic) between frontend and backend applications, storing them in databases, and evaluating them reliably across different environments. It is currently at version 1.0.1 and appears to be in a maintenance phase, focusing on correctness and compliance with the JsonLogic standard.
Warnings
- gotcha The `substr` operator in `panzi-json-logic` operates on Unicode code points, which differs from the `json-logic-js` JavaScript implementation that operates on UTF-16 code units. This can lead to different string slicing behavior for certain non-ASCII strings.
- gotcha The `==` operator attempts to emulate JavaScript's loose equality, which performs type coercion. This can lead to unexpected results if Python's strict `==` behavior is anticipated. For strict equality, use the `===` operator.
- gotcha JsonLogic rules are standard JSON. Common JSON syntax errors (e.g., trailing commas, unquoted keys, single quotes instead of double quotes, incorrect casing for `true`/`false`/`null`) will cause parsing failures before the logic can be evaluated.
Install
-
pip install panzi-json-logic
Imports
- jsonLogic
from json_logic import jsonLogic
Quickstart
from json_logic import jsonLogic
# Simple rule evaluation
rule_simple = { "==": [1, 1] }
result_simple = jsonLogic(rule_simple)
print(f"Simple rule (1 == 1): {result_simple}")
# Data-driven rule evaluation
rule_data = { ">": [{ "var": "temp" }, 100] }
data = { "temp": 105 }
result_data = jsonLogic(rule_data, data)
print(f"Data-driven rule (temp > 100 with temp=105): {result_data}")
# Custom operations (example: using UTF16_SUBSTR for JS-like substr behavior)
from json_logic.builtins import UTF16_SUBSTR
custom_operations = { 'substr_utf16': UTF16_SUBSTR }
rule_substr = { 'substr_utf16': ['hello world', 0, 5] }
result_substr = jsonLogic(rule_substr, operations=custom_operations)
print(f"Custom substr (hello world, 0, 5): {result_substr}")