Representing logic as data in JSON

前端 未结 12 1468
眼角桃花
眼角桃花 2021-01-29 21:37

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 a

12条回答
  •  再見小時候
    2021-01-29 21:56

    I needed a format that would:

    1. Support comparisons other than equality.
    2. Let variables appear in any position, not just be compared to literals.
    3. Be consistent, terse, secure, and extensible.

    So I built up a format I'm calling JsonLogic. A rule is a JSON object, with the operator in the key position, and one or an array of arguments in the value position. (Inspired by Amazon CloudFormation functions.) Any argument can be another rule, so you can build arbitrarily deep logic.

    I've also written two parsers for it: JsonLogic for JavaScript and JsonLogic for PHP.

    cHao's example would be written as

    { "and", [
        {"==", [ {"var" : "var1"}, "value1" ]},
        { "or", [
            {"==", [ {"var" : "var2"}, "value2" ]},
            {"==", [ {"var" : "var3"}, "value3" ]}
        ]}
    ]}
    

    var here is the operator to get a property of the "data" object, passed along with the "rule" object to the parser, e.g.:

    jsonLogic(
        {"==", [{"var":"filling"}, "apple"]}    // rule, is this pie apple?
        {"filling":"apple", "temperature":100}  // data, a pie I'm inspecting
    );
    // true
    

    There are lots more possible operators (greater than, not-equals, in-array, ternary, etc) and both parsers are available on GitHub (with unit tests and documentation).

提交回复
热议问题