Anyone mentioned Jshon or JSON.sh?
https://github.com/keenerd/jshon
pipe json to it, and it traverses the json objects and prints out the path to the current object (as a JSON array) and then the object, without whitespace.
http://kmkeen.com/jshon/
Jshon loads json text from stdin, performs actions, then displays the last action on stdout and also was made to be part of the usual text processing pipeline.
For Bash/Python, here is a basic wrapper around python's simplejson:
json_parser() {
local jsonfile="my_json_file.json"
local tc="import simplejson,sys; myjsonstr=sys.stdin.read(); "`
`"myjson=simplejson.loads(myjsonstr);"
# Build python print command based on $@
local printcmd="print myjson"
for (( argn=1; argn<=$#; argn++ )); do
printcmd="$printcmd['${!argn}']"
done
local result=$(python -c "$tc $printcmd.keys()" <$jsonfile 2>/dev/null \
|| python -c "$tc $printcmd" <$jsonfile 2>/dev/null)
# For returning space-separated values
echo $result|sed -e "s/[]|[|,|']//g"
#echo $result
}
It really only handles the nested-dictionary style of data, but it works for what I needed, and is useful for walking through the json. It could probably be adapted to taste.
Anyway, something homegrown for those not wanting to source in yet another external dependency. Except for python, of course.
Ex. json_parser {field1} {field2} would run print myjson['{field1}']['{field2}'], yielding either the keys or the values associated with {field2}, space-separated.