-
-
Save xamebax/6595617 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 python | |
import json | |
import sys | |
def pp(vv, prefix='$'): # vv = array w/ JSON data, prefix = what's printed at the start of each line | |
if isinstance(vv, (list,tuple)): # if vv is a list/tuple - an Array in Ruby | |
for i, v in enumerate(vv): # vv being enumerated means each array element | |
# is being given an "index", so (a, b, c) => [(0, a), (1, b), (2, c)]... | |
# so for each "index" & "value" pair of the enumerated vv array... | |
pp(v, "{0}[{1}]".format(prefix, i)) # the pp method is called again, only on | |
# the "values"... and I don't get the second part - | |
# one element is printed in square brackets, but which one? | |
elif isinstance(vv, dict): # if vv is a dict - a Hash in Ruby | |
for k,v in sorted(vv.items()): # then for each key&value pair in that sorted Hash | |
pp(v, "{0}.{1}".format(prefix, k)) # the pp method is called again | |
# and the key&value is printed separated by a "."? | |
else: # the `else` case prints out the value after | |
print '{0} = {1}'.format(prefix, json.dumps(vv)) # an `=` sign when there's no nested hash/array left | |
pp(json.load(sys.stdin)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line #11 in Ruby would be
"#{prefix}[#{i}]"
- prefix, then index in square brackets. This makes each element of a sequence (array/list/tuple) printed with an index attached to the prefix; ifprefix = 'foo'``, and
vv = ['a','b','c']`, the the output would be:It's similar for the dictionaries in line 16 -
pp
is called recursively, withvv
set to value, and the lower prefix set to"#{prefix}.#{key}"
to give dotted notation.The line 19, at the leaves of the JSON data tree (when the value provided to
pp
is an atom - a single piece of data, not a sequence or a dictionary, where we cannot recurse deeper), is the only one that actually prints anything to the screen - the final prefix, and value (encoded as JSON to quote any special characters, such as newlines).