Created
May 20, 2015 14:32
-
-
Save Jim-Holmstroem/994f6e1a7b268ddcd085 to your computer and use it in GitHub Desktop.
Filter the keys from first level of a json. Used like "curl yad.da/api/something | ./filter_json.py wanted_key_1 wanted_key_2"
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 | |
from __future__ import print_function, division | |
from operator import itemgetter | |
import sys | |
import json | |
def json_filter(filter_keys, data): | |
def dictionary_filter(filter_keys, dictionary): | |
filter_values = itemgetter(*filter_keys) | |
filtered_values = filter_values(dictionary) | |
return dict( | |
zip( | |
filter_keys, | |
filtered_values, | |
) | |
) | |
return json.dumps( | |
dictionary_filter( | |
filter_keys=filter_keys, | |
dictionary=json.loads(data), | |
) | |
) | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('filter_keys', type=str, nargs="*") | |
arguments = parser.parse_args() | |
print( | |
json_filter( | |
filter_keys=arguments.filter_keys, | |
data=sys.stdin.read() | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment