Using python, I need to convert expressions into JsonLogic format. Expressions such as Boolean expressions, if else / ternary expressions, etc.
Any suggestions how to achieve this ?
P.S. I see that we have a js-to-json-logic
library for the same in Javascript. Could not find its equivalent Python Library.
Example 1:
Input:
((var001 == "Y"))?1:((var001 == "N"))?0:false
Output:
{
"if": [
{
"==": [
{
"var": "var001"
},
"Y"
]
},
1,
{
"if": [
{
"==": [
{
"var": "var001"
},
"N"
]
},
0,
false
]
}
]
}
Example 2:
Input:
CustomFunc(var123, "%Y-%d", (var123 == "N" ? 0 : 123))
Note: Input could be a combination of custom function (having n parameters) and any of these parameters could be single attribute or a combination of further expressions.
Output:
{
"CustomFunc": [
{
"var": "var123"
},
"%Y-%d",
{
"if": [
{
"==": [
{
"var": "var123"
},
"N"
]
},
0,
123
]
}
]
}
Example 3:
Input:
9 + 2 - 6 * 4
Output as per opertor precedence and parenthesis
Pyparsing's infixNotation method will permit the definition of unary, binary, and ternary operators (such as your
expr ? true_value : false_value
operations). This code will parse your given expression:Having the parser is the first half of the battle. This answer continues on to show how to attach classes to the various parsed terms - in that case it was to evaluate the result, but for you, you'll probably want to do something like implement a
as_jsonlogic()
method to these classes to emit equivalent forms for the JsonLogic format.EDIT:
Ok, that may not have been that helpful to just show you the parser. So here is the parser with the added classes, and their respective as_jsonlogic() methods.
Prints:
I'll leave the pretty indentation to you.