Mercurial > hg > config
annotate python/jsonex.py @ 887:79eeb5390c8a
hgignore
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Sat, 24 Apr 2021 14:27:57 -0700 |
parents | 0fa456446fea |
children |
rev | line source |
---|---|
134 | 1 #!/usr/bin/env python |
2 | |
3 """ | |
4 JSON explorer | |
5 """ | |
6 | |
687 | 7 import argparse |
134 | 8 import json |
687 | 9 import os |
134 | 10 import sys |
687 | 11 import urllib2 |
134 | 12 |
692 | 13 def dereference(obj, key): |
14 if obj is None: | |
15 return None | |
16 if isinstance(obj, dict): | |
17 return obj[key] | |
18 return obj[int(key)] | |
19 | |
134 | 20 def main(args=sys.argv[1:]): |
687 | 21 |
22 # command line | |
836
0fa456446fea
use module docstring for description, as intended
Jeff Hammel <k0scist@gmail.com>
parents:
692
diff
changeset
|
23 parser = argparse.ArgumentParser(description=__doc__) |
687 | 24 parser.add_argument('input', nargs='?', |
25 help="input file or url (read from stdin if ommitted)") | |
26 parser.add_argument('object', nargs='*', | |
27 help="object in dotted notation") | |
28 | |
29 options = parser.parse_args(args) | |
134 | 30 |
687 | 31 # get data |
32 if not options.input or options.input == '-': | |
33 data = sys.stdin | |
34 elif'://' in options.input: | |
35 data = urllib2.urlopen(options.input) | |
36 else: | |
37 data = open(options.input, 'r') | |
38 obj = json.load(data) | |
39 | |
40 if options.object: | |
41 for o in options.object: | |
689 | 42 base = obj |
692 | 43 for key in o.strip().split('.'): # split into objects |
44 base = dereference(base, key) | |
45 if base is None: | |
46 break | |
47 print (json.dumps(base)) | |
134 | 48 else: |
692 | 49 print (json.dumps(obj, indent=2, sort_keys=True)) |
134 | 50 |
51 if __name__ == '__main__': | |
52 main() |