Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to robustly describe conditional expressions with AND, OR in JSON?

Say I have an expression:

( A >= 10 && B == 20 ) || ( C < 30 ) || ( D != 50 )

I can suggest the following JSON to store/represent this expression:

{ "filter": 
    [
        { "var":"A", "condition":"ge", "num":10 },
        { "var":"B", "condition":"e", "num":20 }
    ],
    [
        { "var":"C", "condition":"lt", "num":30 }
    ],
    [
        { "var":"D", "condition":"ne", "num":50 }
    ]
}

in which "filter" maps to an array of sub-arrays. All elements in each sub-array are associated with AND, while all sub-arrays are associated with OR.

Is there anything I've overlooked in writing the JSON like this?

like image 767
lichgo Avatar asked Mar 29 '15 13:03

lichgo


1 Answers

You're making a couple of assumptions here:

  1. Comparisons will be always be between a variable and a number, and never between two variables or two numbers.
  2. The variable will always be on the left hand side of the comparison, and the number on the right.

Those assumptions may be correct for your particular use case, but a more future-proof approach would be to treat comparisons similarly to functions with arguments:

{ "ge": ["A", 10] }

Also, while your idea of using an array of objects to represent AND and an array of arrays to represent OR is clever, it might not be immediately obvious to a human being tasked with writing code to parse it. Reusing the idea of an object where the key represents a function and its associated value the arguments is more expressive:

{ "all": [<condition 1>, <condition 2>, ...] }

Putting those two ideas together, we get something like this:

{ "any": [
    { "all": [
        { "ge": ["A", 10] },
        { "eq": ["B", 20] }
    ]},
    { "lt": ["C", 30] },
    { "ne": ["D", 50] }
]}
like image 69
Zero Piraeus Avatar answered Oct 14 '22 04:10

Zero Piraeus