Last active
July 16, 2018 10:08
-
-
Save ivan/4c5fd23a5d06d2d339442cba6fdc365a to your computer and use it in GitHub Desktop.
gron in Python
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
#!/usr/bin/python3 -SB | |
import re | |
import sys | |
import json | |
def main(): | |
o = json.loads(sys.stdin.read()) | |
gron(["json"], o) | |
def gron(path, o): | |
if isinstance(o, dict): | |
print("%s = {};" % format_path(path)) | |
for k in sorted(o): | |
gron(path + [k], o[k]) | |
elif isinstance(o, list): | |
print("%s = [];" % format_path(path)) | |
for n, v in enumerate(o): | |
gron(path + [n], v) | |
else: | |
print("%s = %s;" % (format_path(path), json.dumps(o))) | |
def format_path(path): | |
out = "" | |
for n, seg in enumerate(path): | |
if can_leave_unquoted(seg): | |
dot = "." if n else "" | |
out += "%s%s" % (dot, seg) | |
else: | |
out += "[%s]" % json.dumps(seg) | |
return out | |
identifier_re = re.compile(r"\A[_$A-Za-z][_$A-Za-z0-9]*\Z") | |
reserved_words = set(""" | |
break case catch class const continue debugger default delete do else export | |
extends false finally for function if import in instanceof new null return | |
super switch this throw true try typeof var void while with yield | |
""".split()) | |
def can_leave_unquoted(key): | |
if isinstance(key, int): | |
return False | |
elif key in reserved_words: | |
return False | |
elif re.match(identifier_re, key): | |
return True | |
else: | |
return False | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Moved to https://github.com/ludios/quickmunge/blob/master/bin/gron