Skip to content

Instantly share code, notes, and snippets.

@jkmacc-LANL
Last active January 28, 2017 01:23
Show Gist options
  • Save jkmacc-LANL/2d9fda06872ecda0518fc81a5194744d to your computer and use it in GitHub Desktop.
Save jkmacc-LANL/2d9fda06872ecda0518fc81a5194744d to your computer and use it in GitHub Desktop.
JSONVisitor
import json
from parsimonious import Grammar, NodeVisitor
class JSONVisitor(NodeVisitor):
"""
A simple JSON serializer for Parsimonious parse trees.
"""
def generic_visit(self, node, children):
if node.expr_name:
out = OrderedDict(expr_name=node.expr_name, text=node.text,
start=node.start, end=node.end)
if children:
out['children'] = children
else:
if children:
out = children
else:
out = None
return out
if __name__ == '__main__':
my_grammar = Grammar(r"""
styled_text = bold_text / italic_text
bold_text = "((" text "))"
italic_text = "''" text "''"
text = ~"[A-Z 0-9]*"i
""")
tree = my_grammar.parse("((bold stuff))")
visited = JSONVisitor().visit(tree)
print(json.dumps(visited, indent=2))
""" returns:
{
"expr_name": "styled_text",
"text": "((bold stuff))",
"start": 0,
"end": 14,
"children": [
{
"expr_name": "bold_text",
"text": "((bold stuff))",
"start": 0,
"end": 14,
"children": [
null,
{
"expr_name": "text",
"text": "bold stuff",
"start": 2,
"end": 12
},
null
]
}
]
}
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment