将简单表达式转换为jsonlogic格式
使用Python,我需要将表达式转换为 jsonlogic 格式。诸如布尔表达的表达,如果其他 /三元表达式等。
如何实现这一目标?
ps我看到我们有一个js-to-json-logic
库在JavaScript中相同。找不到其等效的Python库。
示例1:
输入:
((var001 == "Y"))?1:((var001 == "N"))?0:false
输出:
{
"if": [
{
"==": [
{
"var": "var001"
},
"Y"
]
},
1,
{
"if": [
{
"==": [
{
"var": "var001"
},
"N"
]
},
0,
false
]
}
]
}
示例2:
输入:
CustomFunc(var123, "%Y-%d", (var123 == "N" ? 0 : 123))
注意:输入可以是自定义函数(具有n个参数)的组合,并且这些参数中的任何一个都可以是单个属性或进一步表达式的组合。
输出:
{
"CustomFunc": [
{
"var": "var123"
},
"%Y-%d",
{
"if": [
{
"==": [
{
"var": "var123"
},
"N"
]
},
0,
123
]
}
]
}
示例3:
输入:
9 + 2 - 6 * 4
按Opertor优先级和括号的输出
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Pyparsing的InfixNotation方法将允许定义一元,二进制和三元运算符(例如您的
expr?true_value:false_value
operations)。该代码将解析您的表达式:让解析器是战斗的前半部分。 这个答案情况是评估结果,但是对于您来说,您可能想执行这些类别的
AS_JSONLOGIC()
方法,以散发JSONLOGIC格式的等效表格。编辑:
好的,只向您展示解析器可能没有什么帮助。因此,这是带有添加类的解析器及其各自的AS_JSONLOGIC()方法。
印刷品:
我将漂亮的凹痕留给您。
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.