Skip to content

Instantly share code, notes, and snippets.

@quiye
Created July 5, 2021 19:27
Show Gist options
  • Save quiye/9d567ec18b01c4cb614f4d1728b961db to your computer and use it in GitHub Desktop.
Save quiye/9d567ec18b01c4cb614f4d1728b961db to your computer and use it in GitHub Desktop.
json arg searcher
import json
from typing import Dict, List, Any
import sys
if len(sys.argv) != 2:
raise Exception("invalid args")
id = sys.argv[1]
def check(name: str, a: Any, isPrintable: bool = False, path: str = "") -> None:
if isinstance(a, dict):
for k, v in a.items():
if k == name:
check(name, v, True, path+"."+str(k))
else:
check(name, v, isPrintable, path+"."+str(k))
elif isinstance(a, list):
for i in a:
check(name, i, isPrintable, path+'[]')
elif isPrintable:
print(path + '.' + str(a))
elif str(a) == name:
check(name, a, True, path)
for line in sys.stdin:
a = json.loads(line)
check(id, a)
@quiye
Copy link
Author

quiye commented Jul 5, 2021

vscode  /workspaces/markdown-table-to-json (master ) $ echo '{"hoge":[{"huga":"papi"},{"pope":999}]}' | python main.py 999
.hoge[].pope.999
vscode  /workspaces/markdown-table-to-json (master ) $ echo '{"hoge":[{"huga":"papi"},{"pope":999}]}' | python main.py pope
.hoge[].pope.999
vscode  /workspaces/markdown-table-to-json (master ) $ echo '{"hoge":[{"huga":"papi"},{"pope":999}]}' | python main.py hoge
.hoge[].huga.papi
.hoge[].pope.999
vscode  /workspaces/markdown-table-to-json (master ) $ echo '{"hoge":[{"huga":"papi"},{"pope":999}]}' | python main.py zzz
vscode  /workspaces/markdown-table-to-json (master ) $ echo '{"hoge":[{"huga":"papi"},{"pope":999}]}' | python main.py zzz yyy
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    raise Exception("invalid args")
Exception: invalid args

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment