1:46PM February 15, 2011: A json parser for the shell.
Jshon parses, reads and creates JSON. It is designed to be as usable as possible from within the shell and replaces fragile adhoc parsers made from grep/sed/awk. Requires Jansson
- Download jshon.tar.gz * Forum thread
- Github * Forum thread
- AUR
- Github
It loads json text from stdin, performs actions, then dumps to stdout. Some of the options output json, others output plain text summaries. Because Bash has very poor nested datastructures, Jshon is a breadth-first parser and all actions work on the outermost element. Actions may be chained sequentially to reduce calls to jshon.
ACTIONS
Each action takes the form of a short option. Some require arguments. All examples will work on this json sample:
{"a":1,"b":[true,false,null,"none"],"c":{"d":4,"e":5}}
jshon [actions] < sample.json
-t
(type) returns string, object, list, number, bool, null
jshon -t -> object
-l
(length) returns an integer. Only works on string, object, list.
jshon -l -> 3
-k
(keys) returns a newline separated list of keys. Only works on object.
jshon -k -> a b c
-e index
(extract) returns json value at "index". Only works on object, list.
jshon -e c -> {"d":4,"e":5}
-s value
(string) returns a json encoded string. Ignores stdin.
jshon -s "back\slash" -> "back\\slash"
-u
(unstring) returns a decoded string. Only works on string.
jshon -e b -e 3 -u -> none
-m index,value
(modify) edits an element in a list or a dict. Value must be escaped. If value is remove, delete the index. If value is true/false/null, insert the primitive type. Quoting strings is optional, except for the ambiguous case of remove/true/false/null. Lists support several magic indexes. Negative numbers wrap around the back, and append will add a new element after the last.
jshon -m a,first -> {"a":"first", ...}
-i index
(insert) is complicated. It is the reverse of extract. Extract saves a copy of the json on a stack. Insert pops json from the stack, and inserts that bit of json into the new top of the stack. Use extract to dive into the json tree, modify to change something, and insert to push the changes back up the tree.
jshon -e a -i a -> the orginal json
jshon -e b -m 2,remove -m 2,remove -m append,1.2 -i b ->
{"a":1, "b":[true,false,1.2], "c":{"d":4,"e":5}}
BUGS
Numerous! There are no stack over/underflow checks. Forward slashes are not escaped. Object indexes with commas are broken. On any error it exits without saying why. Documentation is very brief.