JSON-Logic
json-logic-py is a Python implementation of JsonLogic, a lightweight JSON-based rules engine. It allows users to build complex logic rules using a JSON structure, serialize them, and execute them in Python to evaluate data. The current version is 0.6.3, and it appears to be in a stable maintenance phase with infrequent updates, requiring Python 3.6+.
Warnings
- breaking The behavior of the `in` operator changed in version 0.6.0. Previously, it might have checked for substring presence in a string. Since 0.6.0, `in` strictly checks for element presence within a list.
- gotcha JsonLogic rules must strictly adhere to the defined JSON structure, where operator keys are always single keys in an object, and their values are arrays of arguments. Deviations will lead to errors or unexpected behavior.
- gotcha When receiving JsonLogic rules from untrusted sources (e.g., user input), there's a potential for logic bombs or resource exhaustion if highly complex or deeply nested rules are submitted. While the library itself doesn't execute arbitrary code, poorly constructed rules can still impact performance.
- gotcha Custom operators must be explicitly registered with the `add_operation` function before they can be used in your rules. They are not automatically discovered.
Install
-
pip install json-logic
Imports
- jsonLogic
from json_logic import jsonLogic
Quickstart
from json_logic import jsonLogic
rules = {
"and": [
{"<": [1, 2]},
{">": [1, 0]}
]
}
data = {}
result = jsonLogic(rules, data)
print(f"Result: {result}")
# Example with actual data
user_data = {"temp": 100, "humidity": 50}
rules_with_var = {
"and": [
{"<": [{"var": "temp"}, 150]},
{"<=": [{"var": "humidity"}, 60]}
]
}
result_with_data = jsonLogic(rules_with_var, user_data)
print(f"Result with data: {result_with_data}")