Created
April 10, 2013 09:50
-
-
Save onjin/5353305 to your computer and use it in GitHub Desktop.
json grep utility
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
#!/usr/bin/env python | |
import sys | |
import re | |
import json | |
def jsongrep(d, patterns): | |
try: | |
pattern = patterns.pop(0) | |
except IndexError: | |
print json.dumps(d, indent=4) | |
else: | |
if isinstance(d, dict): | |
keys = filter(pattern.match, d.keys()) | |
elif isinstance(d, list): | |
keys = map(int, | |
filter(pattern.match, | |
['%d' % i for i in range(len(d))])) | |
else: | |
if pattern.match(str(d)): | |
print json.dumps(d, indent=4) | |
return | |
for item in (d[key] for key in keys): | |
jsongrep(item, patterns[:]) | |
if __name__ == '__main__': | |
try: | |
j = json.loads(sys.stdin.read()) | |
except ValueError, e: | |
print >>sys.stderr, 'Could not load JSON object from stdin.' | |
sys.exit(1) | |
jsongrep(j, map(re.compile, sys.argv[1:])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment