Skip to content

Instantly share code, notes, and snippets.

@ivan
Last active July 16, 2018 10:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan/4c5fd23a5d06d2d339442cba6fdc365a to your computer and use it in GitHub Desktop.
Save ivan/4c5fd23a5d06d2d339442cba6fdc365a to your computer and use it in GitHub Desktop.
gron in Python
#!/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()
@ivan
Copy link
Author

ivan commented Jul 16, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment