Package: panzi-json-logic
panzi-json-logicPure Python 3JsonLogicandCertLogicimplementation.The JsonLogic format is designed to allow you to share rules (logic) between
front-end and back-end code (regardless of language difference), even to store
logic along with a record in a database. JsonLogic is documented atJsonLogic.com, including examples of everysupported operationand a place totry out rules in your browser.CertLogic is a dialect of JsonLogic with slightly different semantics and
operations.There are already other JsonLogic implementations in Python, but last I looked
they don't emulate all the JavaScript operator behaviors quite right and they
don't implement CertLogic at all. This implementation tries to be as close to
theJavaScript implementationof
JsonLogic as feasible.InstallationExamplesSimpleCompoundData-DrivenAlways and NeverCertLogicCustom OperationsExtrasRemarksCreditsInstallationInstall this package via pypi:pipinstallpanzi-json-logicExamplesSimplefromjson_logicimportjsonLogicjsonLogic({"==":[1,1]})# TrueThis is a simple test, equivalent to1 == 1. A few things about the format:The operator is always in the "key" position. There is only one key per
JsonLogic rule.The values are typically an array.Each value can be a string, number, boolean, array (non-associative), or nullNote that==tries to emulate the JavaScript==operator and as such it is
adviseable to rather use===, which in this implementations simply uses
Python's==.CompoundHere rules are nested.jsonLogic({"and":[{">":[3,1]},{"<":[1,3]}]})# TrueIn an infix language (like Python) this could be written as:((3>1)and(1<3))Data-DrivenObviously these rules aren't very interesting if they can only take static
literal data. TypicallyjsonLogic()will be called with a rule object and a
data object. You can use thevaroperator to get attributes of the data object:jsonLogic({"var":["a"]},# Rule{a:1,b:2}# Data)# 1If you like,syntactic sugaron unary operators to skip the array around values is supported:jsonLogic({"var":"a"},{a:1,b:2})# 1You can also use thevaroperator to access an array by numeric index:jsonLogic({"var":1},["apple","banana","carrot"])# "banana"Here's a complex rule that mixes literals and data. The pie isn't ready to eat
unless it's cooler than 110 degrees,andfilled with apples.rules={"and":[{"<":[{"var":"temp"},110]},{"==":[{"var":"pie.filling"},"apple"]}]}data={"temp":100,"pie":{"filling":"apple"}}jsonLogic(rules,data)# TrueAlways and NeverSometimes the rule you want to process is "Always" or "Never." If the first
parameter passed tojsonLogic()is a non-object, non-associative-array, it is
returned immediately.# AlwaysjsonLogic(True,data_will_be_ignored)# True# NeverjsonLogic(False,i_wasnt_even_supposed_to_be_here)# FalseCertLogicCertLogic is implemented in thejson_logic.cert_logicsub-module:fromjson_logic.cert_logicimportcertLogiccertLogic({"plusTime":["2022-01-02T15:00:00+02:00",2,"day"]}).isoformat()# '2022-01-04T15:00:00+02:00'Custom OperationsIn contrast to other JsonLogic implementations you are not supposed to
manipulate the libraries dictionary of operations, but instead pass your own
dictionary as optional 3rd argument tojsonLogic(). If you want to use
the predefined operations you have to manually include them:fromjson_logicimportjsonLogicfromjson_logic.builtinsimportBUILTINSops={**BUILTINS,'pow':lambdadata,a,b:a**b}jsonLogic({'pow':[3,2]},None,ops)# 9Note that in contrast to other Python JsonLogic libraries the data as passed to
thejsonLogic()function (or the context data inmap/filter/reduce/all/some/none) is passed to operator functions as
the first argument (you can call itselfif you want to, to be consistent with
the JavaScript implementation where it is thethisargument).Note that not all operations can be overwritten with the operations dictionary.
In particular these operations are hard coded in because of their short circuit
behavior or because they execute one operand on all the items of a list:if(alternative spelling:?:),and,or,map,filter,reduce,all,some,none.ThecertLogic()function can be called in the same way with extra operations.
The CertLogic builtins can be found underjson_logic.cert_logic.builtins.BUILTINS.ExtrasThis library also includes some extra operators that are not part of JsonLogic.
You can find them underjson_logic.extras.EXTRAS. This dictionary already
includesjson_logic.builtins.BUILTINS. The same extras but combined withjson_logic.cert_logic.builtins.BUILTINScan be found underjson_logic.cert_logic.extras.EXTRAS. The CertLogic extras also include all the
operations from JsonLogic that are otherwise missing from CertLogic, but with
CertLogic semantics for!and!!(i.e. empty objects are falsy in CertLogic,
but truthy in JsonLogic).nowRetrieve current time as Pythondatetimeobject in UTC.{
    "now": []
}Example:fromjson_logicimportjsonLogicfromjson_logic.extrasimportEXTRASjsonLogic({"now":[]},None,EXTRAS)# datetime.datetime(2021, 9, 12, 0, 31, 25, 419443, tzinfo=datetime.timezone.utc)parseTimeParse RFC 3339 date and date-time strings. Date-time strings without an explicit
time zone offset are assumed to be in UTC.{
    "parseTime": [
        <string-or-datetime>
    ]
}Example:jsonLogic({"parseTime":"2022-01-02"},None,EXTRAS)# datetime.datetime(2022, 1, 2, 0, 0, tzinfo=datetime.timezone.utc)jsonLogic({"parseTime":"2022-01-02T15:00:00+02:00"},None,EXTRAS)# datetime.datetime(2022, 1, 2, 15, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))NOTE:You need to useparseTimebefore comparing actualdatetimeobjects with
date-times provided as a string or you'll get wrong results. Assume the current
time is somewhen in 2021:jsonLogic({"<":[{"now":[]},"2022-01-02"]},None,EXTRAS)# FalsejsonLogic({"<":[{"now":[]},{"parseTime":"2022-01-02"}]},None,EXTRAS)# TrueHowever CertLogic has operators that are doing that for you:fromjson_logicimportcertLogicfromjson_logic.cert_logic.extrasimportEXTRAScertLogic({"before":[{"now":[]},"2022-01-02"]},None,EXTRAS)# TrueNote thatjson_logic.cert_logic.extras.EXTRAS(to getnow) is used withcertLogic.timeSinceMilliseconds since given date-time.{
    "timeSince": [
        <string-or-datetime>
    ]
}Exmaple:jsonLogic({"timeSince":"2021-01-02T15:00:00+02:00"},None,EXTRAS)# 21814538195.281hoursConvert hours to milliseconds. Useful in combination withtimeSince.{
    "hours": [
        <number>
    ]
}Example:jsonLogic({"hours":2},None,EXTRAS)# 7200000daysConvert days to milliseconds. Useful in combination withtimeSince.{
    "hours": [
        <number>
    ]
}Example:jsonLogic({"days":2},None,EXTRAS)# 172800000combinationsReturn array of arrays that represent all combinations of the elements of all
the lists.{
    "combinations": [
        <array>...
    ]
}Example:fromjson_logicimportjsonLogicfromjson_logic.extrasimportEXTRASjsonLogic({"combinations":[[1,2,3],["a","b","c"],["x","y","z"],]},None,EXTRAS)# [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]zipLike Python'szip(), but returns array of arrays (instead of generator of
tuples).{
    "zip": [
        <array>...
    ]
}Example:jsonLogic({"zip":[[1,2],["a","b"],]},None,EXTRAS)# [[1, 'a'], [2, 'b']]RemarksThere is currently one known way where this implementation differs from theJavaScript implementationof
JsonLogic: Thesubstroperator in this implementation operates on code points,
but in json-logic-js it operates on UTF-16 code units. To emulate this in
Python an UTF-16 encode/decode round-trip is needed insubstr, and even then
there are differences where Python disallows broken UTF-16, but JavaScript
allows it.But if you really want the JavaScript behavior this library provides an
alternativesubstrimplementation that does the UTF-16 round-trip. You can use
it like this:fromjson_logicimportjsonLogicfromjson_logic.builtinsimportBUILTINS,op_substr_utf16result=jsonLogic(logic,data,{**BUILTINS,'substr':op_substr_utf16})CreditsSome of this README is copied fromjson-logic-py,
some of the tests are ported fromjson-logic-jsand theJsonLogic test suiteand theCertLogic test suiteare included in the tests of this library.