-
Notifications
You must be signed in to change notification settings - Fork 39
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add transformer * Refer to JSONTransformer in README
- Loading branch information
Showing
2 changed files
with
79 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
from lark import Transformer | ||
from lark.lexer import Token | ||
|
||
|
||
class JSONTransformer(Transformer): | ||
def __init__(self, compact=False): | ||
self.compact = compact | ||
super().__init__() | ||
|
||
def __default__(self, data, children): | ||
items = [] | ||
for c in children: | ||
if isinstance(c, Token): | ||
token_repr = { | ||
"@module": "lark.lexer", | ||
"@class": "Token", | ||
"type_": c.type, | ||
"value": c.value, | ||
} | ||
if self.compact: | ||
del token_repr["@module"] | ||
del token_repr["@class"] | ||
items.append(token_repr) | ||
elif isinstance(c, dict): | ||
items.append(c) | ||
else: | ||
raise ValueError(f"Unknown type {type(c)} for tree child {c}") | ||
tree_repr = { | ||
"@module": "lark", | ||
"@class": "Tree", | ||
"data": data, | ||
"children": items, | ||
} | ||
if self.compact: | ||
del tree_repr["@module"] | ||
del tree_repr["@class"] | ||
return tree_repr |