Created
May 7, 2021 10:50
-
-
Save rh314/2b52af76bae9b62c2ed47c32d83198c1 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
''' | |
Run the script, then paste a "python-like" dictionary as input and press enter. | |
The script will output the json parseable version of the input. | |
''' | |
import json | |
import ast | |
def transform(obj): | |
if isinstance(obj, ast.Module): | |
assert(len(obj.body) == 1) # for converting to json-like | |
return transform(obj.body[0]) | |
elif isinstance(obj, ast.Expr): | |
return transform(obj.value) | |
elif isinstance(obj, ast.Dict): | |
keys = [transform(_) for _ in obj.keys] | |
vals = [transform(_) for _ in obj.values] | |
return dict(zip(keys, vals)) | |
elif isinstance(obj, ast.List): | |
return [transform(_) for _ in obj.elts] | |
elif isinstance(obj, ast.Constant): | |
return obj.value | |
else: | |
raise Exception('TODO') | |
src = '' | |
while True: | |
inpt = input() | |
if inpt == '': | |
break | |
src += inpt | |
parsed = ast.parse(src) | |
converted = transform(parsed) | |
print('\nResult:') | |
print(json.dumps(converted, indent=2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment