I am trying to create JSON from a string with an expression, but before that I have to replace the operand.
This is user input:
"Apple == 5 & (Plum == 7 | Pear == 8)"
I have to replace "==" to "eq", "&" to "and", etc. (and more logical expressions if it is necessary)
"Apple eq 5 and (Plum eq 7 or Pear eq 8)"
And finally, it should be a result in JSON, like this:
{
"CategoryId": 0,
"FilterRequest":
{
"Page": 1,
"PageSize": 10,
"Filter":
{
"Logic": "and",
"Filters": [
{
"Logic": "or",
"Filters": [
{
"Field": "Plum",
"Operator": "eq",
"Value": "7"
},
{
"Field": "Pear",
"Operator": "eq",
"Value": "8"
}
]
},
{
"Field": "Apple",
"Operator": "eq",
"Value": "5"
}
]
}
}
}
Could you tell me your ideas how to do it? Thank you
EDITED : 14/5/2019
I tried to find as much information as possible about my problem and I think I'm halfway. If I ever chose the right way. Could you give me feedback or advice about the code below?
string = "Apple == 5 & (Plum == 7 | Pear == 8)"
string = string.replace('==', ' eq ')
string = string.replace('<>', ' ne ')
string = string.replace('>' , ' gt ')
string = string.replace('>=', ' ge ')
string = string.replace('<' , ' lt ')
string = string.replace('<=', ' le ')
string = string.replace('&' , ' and ')
string = string.replace('|' , ' or ')
string = string.replace('!=', ' not ')
print(string)
# "Apple eq 5 and (Plum eq 7 or Pear eq 8)"
import pyparsing as pp
operator = pp.Regex(r">=|<=|!=|>|<|=|eq").setName("operator")
number = pp.Regex(r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")
identifier = pp.Word(pp.alphas, pp.alphanums + "_")
and_ = CaselessLiteral("and").setResultsName("Logic")
or_ = CaselessLiteral("or").setResultsName("Logic")
not_ = CaselessLiteral("not").setResultsName("Logic")
logic = [
(and_, 2, (pp.opAssoc.LEFT),),
(or_, 2, pp.opAssoc.LEFT,),
(not_, 1, pp.opAssoc.RIGHT,),
]
comparison_term = (identifier | number)
condition = pp.Group(comparison_term("Field") + operator("Operator") + comparison_term("Value"))
expr = pp.operatorPrecedence(condition("Filters"), logic).setResultsName("Filter")
pars = expr.parseString(string).dump()
import json
with open("C:\\Users\\palo173\\Desktop\\example.json","w") as f:
json.dump(o,f)
Actual result, but unfortunately not final. I'd like to hear your ideas as to what to do next.
{
"Filter": {
"Filter": {
"Filters": [
{
"Field": "Apple",
"Operator": "eq",
"Value": "5"
},
{
"Filters": [
{
"Field": "Plum",
"Operator": "eq",
"Value": "7"
},
{
"Field": "Pear",
"Operator": "eq",
"Value": "8"
}
],
"Logic": "or"
}
],
"Logic": "and"
}
}
}