Created
September 25, 2013 02:39
-
-
Save rbscott/6694512 to your computer and use it in GitHub Desktop.
Quick script to parse out fields from a JSON stream
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
import sys | |
import simplejson as json | |
def get_param(js, param=()): | |
if len(param) == 0: | |
return None | |
if len(param) == 1: | |
return js.get(param[0], None) | |
next_value = js.get(param[0], None) | |
if next_value == None or type(next_value) != dict: | |
return None | |
return get_param(next_value, param[1:]) | |
def parse_stream(stream, params): | |
for line in stream: | |
try: | |
js = json.loads(line) | |
values = [str(get_param(js, p.split('.'))) for p in params] | |
print "Values: " + ' '.join(values) | |
except: | |
raise | |
if __name__ == '__main__': | |
parse_stream(sys.stdin, (sys.argv[1:])) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment