Last active
August 29, 2015 14:16
-
-
Save Xorcerer/203200bd5ef24ca018d3 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
def traverse_json(json, predicater, value_getter, name=None): | |
if predicater(name, json): | |
yield value_getter(name, json) | |
if isinstance(json, list): | |
for obj in json: | |
# Use `yield from` instead of for loop in Python 3.x | |
for result in traverse_json(obj, predicater, value_getter): | |
yield result | |
elif isinstance(json, dict): | |
for k, v in json.iteritems(): | |
for result in traverse_json(v, predicater, value_getter, k): | |
yield result | |
def sophia_func(json, key): | |
first, last = key.split('_') | |
def predicate(name, obj): | |
return name == first and isinstance(obj, dict) and last in obj | |
def value_getter(name, obj): | |
return obj[last] | |
return list(traverse_json(json, predicate, value_getter)) | |
def test(): | |
def predicate(name, obj): | |
return name == 'a' and isinstance(obj, dict) and 'b' in obj | |
def value_getter(name, obj): | |
return obj['b'] | |
json = [ | |
{ | |
'a': { | |
'b': 'Hello' | |
}, | |
'b': 'Not me.', | |
'c': {'a': 'b'} | |
}, | |
] | |
result = list(traverse_json(json, predicate, value_getter)) | |
print result | |
assert result == ['Hello'] | |
def test_yield(): | |
def f(): | |
yield 1 | |
yield 2 | |
yield 3 | |
for i in xrange(10): | |
yield i * 10 | |
for i in f(): | |
print i | |
if __name__ == '__main__': | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment