A jsonlogic implementation for Clojure.
[com.nytimes/jsonlogic "1.0.0"]
(require '[com.nytimes.jsonlogic :as jsonlogic])
(jsonlogic/apply {:if [true "Foo" "Bar"]})
"Foo"
This library supports encoding the operators as keywords, string, or symbols. All of these values are coerced to symbols for evalution..
(jsonlogic/apply {"+" [1 2]})
;;=> 3
(jsonlogic/apply {:+ [1 2]})
;;=> 3
(jsonlogic/apply {'+ [1 2]})
;;=> 3
You can add custom JsonLogic operations by extending the operate
multi-method.
Operate receives two arguments, a map of the operation and the data provided to apply. For example, given this invocation:
(jsonlogic/apply {"*" [{"var" "x"} {"var" "x"}]}
{"x" 2})
The arguments to *
are:
{* [{var "x"} {var "x"}]}
{"x" 2}
Here is an example of adding a custom power function.
(require '[com.nytimes.jsonlogic :as json])
(require '[clojure.math :as math])
(defmethod jsonlogic/operate '**
[{args '**} _env]
(if (not= 2 (count args))
(throw (ex-info "** requires exactly two arguments" {:args args}))
(let [[base exponent] args]
(math/pow base exponent))))
(jsonlogic/apply {'** [2 3]})
;;=> 8.0