It's simple enough to write this yourself using recursion. Here is one that creates a list
-- I'll leave the dict
version as an exercise for you.
import sys
import re
def DentArthurDent(fp, dents = 0, nextline = None):
'''Read from FP until EOF or an exdent
Return dict and next line'''
tree = []
while True:
line, nextline = nextline or fp.readline(), None
if not line:
return tree, ''
parts = re.match(r'(^ *)(.*)', line).group(1,2)
dent = len(parts[0])
if dent == dents:
tree.append(parts[1])
elif dent > dents:
child_tree, nextline = DentArthurDent(fp, dent, line)
tree.append(child_tree)
else:
return tree,line
import json
tree, _ = DentArthurDent(sys.stdin)
print json.dumps(tree, indent=4)
This input:
line 1
line 2
line 3
line 4
line 5
line 6
yields this output:
[
"line 1",
"line 2",
[
"line 3",
[
"line 4",
"line 5"
],
"line 6"
]
]