May-10-2019, 09:47 AM
I try to create JSON from logical expression as input from user.
#input from user (for example)
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 + "_")
comparison_term = identifier | number
condition = pp.Group(comparison_term("Field") + operator("Operator") + comparison_term("Value"))
expr = pp.operatorPrecedence(condition("Filters"), [
("and", 2, pp.opAssoc.LEFT, ),
("or", 2, pp.opAssoc.LEFT, ),
("not", 1, pp.opAssoc.RIGHT, ),
]).setResultsName("Filter")
pars = expr.parseString(string).asXML()
import xmltodict, json
o = xmltodict.parse(pars)
with open("C:\\Users\\palo173\\Desktop\\example.json","w") as f:
json.dump(o,f)
f.close()My result in JSON after my code above is:Output:{
"Filter": {
"Filter": {
"Filters": [
{
"Field": "Apple",
"Operator": "eq",
"Value": "5"
},
{
"Filters": [
{
"Field": "Plum",
"Operator": "eq",
"Value": "7"
},
{
"Field": "Pear",
"Operator": "eq",
"Value": "8"
}
],
"ITEM": "or"
}
],
"ITEM": "and"
}
}
}But required result in JSON is:Output:{
"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"
}
]
}
}
}I think that I am fault in my "pyparsing part" of code. Could you help me with it?
