Browse Source

initial commit

master
Jonathan Strong 4 years ago
commit
35e98ccd56
1 changed files with 30 additions and 0 deletions
  1. +30
    -0
      get-json-key.py

+ 30
- 0
get-json-key.py View File

@@ -0,0 +1,30 @@
#!/usr/bin/env python3

import fileinput, sys, json, functools
from typing import Union, List

JsonKey = Union[str, int]

def try_int(x: str) -> JsonKey:
try:
return int(x)
except:
return x

def main(indices: List[str]) -> None:
for line in fileinput.input(files=('-',)):
data = json.loads(line)
try:
val = functools.reduce(lambda x, i: x[try_int(i)], indices, data)
except Exception as e:
print('indexing json data failed with keys {}: {}\n'.format(' > '.join(indices), e), file=sys.stderr)
raise e
print(val)

if __name__ == '__main__':
if len(sys.argv) < 2:
print('USAGE: ./get-json-key.py [KEY].. < json-input', file=sys.stderr)
sys.exit(1)
main(sys.argv[1:])



Loading…
Cancel
Save