Skip to content

Instantly share code, notes, and snippets.

@anaynayak
Last active November 5, 2015 16:37
Show Gist options
  • Save anaynayak/d015a7a1002bcd0e6535 to your computer and use it in GitHub Desktop.
Save anaynayak/d015a7a1002bcd0e6535 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import json
from collections import OrderedDict
opts = {
'format' : 'txt',
'keys' : sys.argv[1:]
}
def json_select(line, keys):
kv = json.loads(line)
if not keys:
return kv
return OrderedDict([(k, kv.get(k)) for k in keys if k in kv])
def process(line, keys):
try:
kv = json_select(line, keys)
if kv:
output(kv)
except ValueError:
pass
def output(kv):
if opts['format'] == 'json':
print json.dumps(kv, indent=4)
elif opts['format'] == 'txt':
print " ".join([str(x) for x in kv.values()])
for line in sys.stdin:
keys = [x.decode('UTF-8') for x in opts['keys']]
process(line, keys)
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment