Skip to content

Instantly share code, notes, and snippets.

@xamebax
Forked from mpasternacki/json2path.py
Last active December 23, 2015 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xamebax/6595617 to your computer and use it in GitHub Desktop.
Save xamebax/6595617 to your computer and use it in GitHub Desktop.
#!/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))
@mpasternacki
Copy link

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; if prefix = 'foo'``, andvv = ['a','b','c']`, the the output would be:

foo[0] = "a" # v='a', i=0, prefix='foo' -> pp('a', 'foo[0]')
foo[1] = "b" # v='b', i=1, prefix='foo' -> pp('b', 'foo[1]')
foo[2] = "c" # v='c', i=2, prefix='foo' -> pp('c', 'foo[2]')

It's similar for the dictionaries in line 16 - pp is called recursively, with vv 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).

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