Python Forum
parsing logical expression with pyparsing - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: parsing logical expression with pyparsing (/thread-18238.html)



parsing logical expression with pyparsing - palo173 - May-10-2019

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? Sad


RE: parsing logical expression with pyparsing - Larz60+ - May-10-2019

check this out, similar application: https://stackoverflow.com/a/32975160


RE: parsing logical expression with pyparsing - palo173 - May-13-2019

(May-10-2019, 03:58 PM)Larz60+ Wrote: check this out, similar application: https://stackoverflow.com/a/32975160

I looked at it, but it didn't really help me.