For business reasons we need to externalize some conditional logic into external files: preferably JSON.
A simple filter-by scenario could be handled by adding a node as follows:
"filter": [ { "criteria": "status", "value": "open", "condition": "==" } ]
Multiple conditions could be handled by additional values in the array.
"filter": [ { "criteria": "status", "value": "open", "condition": "==" }, { "criteria": "condition2", "value": "value2", "condition": "==" } ]
However, it gets a little confusing when we have handle complex conditions involving ANDs or ORs.
Question: is there a standardized (or even widely accepted) format for representing such logic within JSONs? How would you do it if it were up to you?
NOTE: The first answer has been made an editable wiki so it can be improved by anyone who feels it can be.
If you're looking for a way to share logic between front-end and back-end code, and even store it in a database, JsonLogic might be a fit for you. JsonLogic isn't a full programming language. It's a small, safe way to delegate one decision. You could store a rule in a database to decide later.
JSON documents consist of fields, which are name-value pair objects. The fields can be in any order, and be nested or arranged in arrays. Db2® can work with JSON documents in either their original JSON format or in the binary-encoded format called BSON (Binary JSON).
If you must implement this using standard JSON, i'd recommend something akin to Lisp's "S-expressions". A condition could be either a plain object, or an array whose first entry is the logical operation that joins them.
For example:
["AND", {"var1" : "value1"}, ["OR", { "var2" : "value2" }, { "var3" : "value3" } ] ]
would represent var1 == value1 AND (var2 == value2 OR var3 == value3)
.
If you prefer brevity over consistency, you could also allow an object to have multiple properties, which would implicitly be joined by an AND. For example, { "a": "b", "c": "d" }
would be equivalent to ["AND", { "a": "b" }, { "c": "d" }]
. But there are cases (like the example) where the former syntax can not faithfully represent the condition as written; you'd need additional trickery like translating the condition or using dummy property names. The latter syntax should always work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With