Reputation: 12138
Have anyone implemented pretty printing (preferrably using Python's builtin pprint
module) of parse-trees outputted from PyParsing preferrably with indentation and alignment?
Upvotes: 3
Views: 1035
Reputation: 33
You can use json for this.
import json
class PyParseEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, ParseResults):
x = obj.asDict()
if x.keys():
obj = x
else:
x = obj.asList()
if len(x) == 1:
obj = x[0]
else:
obj = x
else:
obj = super(PyParseEncoder, self).default(obj)
return obj
And then
print json.dumps(parseresult, cls=PyParseEncoder, sort_keys=False, indent=2)
If you are getting error from json.dumps just add additional handler to encoder for specific data type.
Upvotes: 1