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?
You're making a couple of assumptions here:
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] }
]}
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