The function you are looking for is important in pyparsing - setting up result names. The use of result names is recommended for most application programs. This feature exists since version 0.9, since
expr.setResultsName("abc")
This allows me to access this particular field of general parsed results like res["abc"] or res.abc (where res is the value returned from parser.parseString ). You can also call res.dump() to see a nested representation of your results.
However, while parsers are easy to follow right away, I added support for this form of setResultsName in 1.4.6:
expr("abc")
Here is your parser with a little cleanup, and the result names are added:
COMMA,LPAR,RPAR = map(Suppress,",()") field = Word(alphanums) value = Word(alphanums) eq_ = CaselessLiteral('eq')("name") + Group(LPAR + field + COMMA + value + RPAR)("args") ne_ = CaselessLiteral('ne')("name") + Group(LPAR + field + COMMA + value + RPAR)("args") function = ( eq_ | ne_ ) arg = Forward() and_ = Forward() or_ = Forward() exp = Group(and_ | or_ | function) arg << delimitedList(exp) and_ << Literal("and")("name") + LPAR + Group(arg)("args") + RPAR or_ << Literal("or")("name") + LPAR + Group(arg)("args") + RPAR
Unfortunately, dump () only handles nesting of results, not lists of values, so it's not as good as json.dumps (maybe this would be a good improvement for dumping?). So, here is a custom method for drop-down results of nested names: args:
ob = exp.parseString("and(or(eq(x,1), eq(x,2)), eq(y,3))")[0] INDENT_SPACES = ' ' def dumpExpr(ob, level=0): indent = level * INDENT_SPACES print (indent + '{') print ("%s%s: %r," % (indent+INDENT_SPACES, 'name', ob['name'])) if ob.name in ('eq','ne'): print ("%s%s: %s" % (indent+INDENT_SPACES, 'args', ob.args.asList())) else: print ("%s%s: [" % (indent+INDENT_SPACES, 'args')) for arg in ob.args: dumpExpr(arg, level+2) print ("%s]" % (indent+INDENT_SPACES)) print (indent + '}' + (',' if level > 0 else '')) dumpExpr(ob)
Donation:
{ name: 'and', args: [ { name: 'or', args: [ { name: 'eq', args: ['x', '1'] }, { name: 'eq', args: ['x', '2'] }, ] }, { name: 'eq', args: ['y', '3'] }, ] }