Last active
November 9, 2015 13:58
-
-
Save yousefhamza/8be5a5e934e12135b476 to your computer and use it in GitHub Desktop.
Python script to parse tabbed files into JSON formats as {'name': <name>, 'children': [] }
This file contains hidden or 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
__author__ = 'yousefhamza' | |
import json | |
import sys | |
if len(sys.argv) != 2: | |
print 'Usage: python parse_tabs.py <file name>' | |
exit() | |
tab_file = open(sys.argv[1]) | |
json_stack = [] | |
current_level, next_level = -1, 0 | |
for line in tab_file.readlines(): | |
next_level = line.count('\t') | |
node = { | |
'name': line.strip('\t').strip('\n'), | |
'children': [], | |
} | |
if next_level > current_level: | |
if json_stack: | |
parent_dict = json_stack[-1] | |
parent_dict['children'].append(node) | |
json_stack.append(node) | |
elif next_level == current_level: | |
parent_dict = json_stack[-2] | |
parent_dict['children'].append(node) | |
json_stack.pop() | |
json_stack.append(node) | |
else: | |
for i in range(next_level, current_level + 1): | |
json_stack.pop() | |
parent_dict = json_stack[-1] | |
parent_dict['children'].append(node) | |
json_stack.append(node) | |
current_level = next_level | |
print json.dumps(json_stack[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment