-
Notifications
You must be signed in to change notification settings - Fork 0
/
grepjson
executable file
·35 lines (32 loc) · 885 Bytes
/
grepjson
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#! /usr/bin/python2.6
import re
import sys
import json
fields = []
for field_pair in sys.argv[1].split(','):
field_name, value = None, None
if '=' in field_pair:
field_name, value = field_pair.split('=')
else:
field_name = field_pair
fields.append((field_name, value))
filehandles = [sys.stdin]
if len(sys.argv) > 2:
filehandles = []
for filename in sys.argv[2:]:
filehandles.append(open(filename))
for fh in filehandles:
for line in fh:
j = json.loads(line)
result = []
for field_name, value in fields:
if value is not None:
if re.search(value, str(j[field_name])):
print line,
else:
field_value = j.get(field_name, '')
if isinstance(field_value, basestring):
result.append(field_value.encode('utf-8'))
else:
result.append(str(field_value))
print '\t'.join(result)