11#!/usr/bin/env python3
2+ import argparse
23import json
34import sys
45from pathlib import Path
78from print_requests import read_json_many
89
910
10- def gron (obj , path = "json" ):
11+ def gron (obj , path = "json" , noindex = False ):
1112 """Flatten JSON into greppable assignments.
1213
1314 The path parameter defaults to "json" to match the original gron tool,
@@ -26,6 +27,10 @@ def gron(obj, path="json"):
2627 json.items[0] = "apple";
2728 json.items[1] = "banana";
2829
30+ >>> gron({"items": ["apple", "banana"]}, noindex=True)
31+ json.items[] = "apple";
32+ json.items[] = "banana";
33+
2934 >>> gron({"tasks": [{"libraries": [{"whl": "file.whl"}]}]})
3035 json.tasks[0].libraries[0].whl = "file.whl";
3136
@@ -38,31 +43,34 @@ def gron(obj, path="json"):
3843 print (f"{ path } = {{}};" )
3944 else :
4045 for key in obj :
41- gron (obj [key ], f"{ path } .{ key } " )
46+ gron (obj [key ], f"{ path } .{ key } " , noindex = noindex )
4247 elif isinstance (obj , list ):
4348 if not obj :
4449 print (f"{ path } = [];" )
4550 else :
4651 for i , item in enumerate (obj ):
47- gron (item , f"{ path } [{ i } ]" )
52+ index = "[]" if noindex else f"[{ i } ]"
53+ gron (item , f"{ path } { index } " , noindex = noindex )
4854 else :
4955 print (f"{ path } = { json .dumps (obj )} ;" )
5056
5157
5258def main ():
53- if len (sys .argv ) > 1 :
54- with open (sys .argv [1 ]) as f :
55- content = f .read ()
56- data = read_json_many (content )
57- if len (data ) == 1 :
58- data = data [0 ]
59+ parser = argparse .ArgumentParser ()
60+ parser .add_argument ("--noindex" , action = "store_true" )
61+ parser .add_argument ("file" , nargs = "?" )
62+ args = parser .parse_args ()
63+
64+ if args .file :
65+ content = Path (args .file ).read_text ()
5966 else :
6067 content = sys .stdin .read ()
61- data = read_json_many (content )
62- if len (data ) == 1 :
63- data = data [0 ]
6468
65- gron (data )
69+ data = read_json_many (content )
70+ if len (data ) == 1 :
71+ data = data [0 ]
72+
73+ gron (data , noindex = args .noindex )
6674
6775
6876if __name__ == "__main__" :
0 commit comments