Skip to content

Instantly share code, notes, and snippets.

@jbriales
Created June 23, 2019 19:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbriales/ea475a155f1f7bbb6731e39e8764f1d1 to your computer and use it in GitHub Desktop.
Save jbriales/ea475a155f1f7bbb6731e39e8764f1d1 to your computer and use it in GitHub Desktop.
Toy jq key autocompletion
function jq() {
if [ -f $1 ]; then
FILE=$1; shift
# Move FILE at the end as expected by native jq
command jq "$@" "$FILE"
else
command jq "$@"
fi
}
function _jq() {
COMPREPLY=()
local curr prev
curr=$2
prev=$3
#set -x
case $COMP_CWORD in
1)
COMPREPLY=( $(compgen -f -- $curr) )
;;
2)
keys=$(command jq -c ". | keys" $prev | grep -P '(?<=")(\w+)(?=")' -o | sed 's=^=\.=')
COMPREPLY=( $(compgen -W "$keys" -- $curr ) )
;;
esac
}
complete -F _jq jq
@jbriales
Copy link
Author

Toy project to autocomplete json file keys in jq.

  • Source the above in your shell
  • Create a toy json file,
    e.g. echo '{"foo":1,"bar":2,"quz":3}' > toy
  • Now you can do autocompletion on keys like this:
    jq toy .<TAB> -> prints autocompletion options: .bar .foo .quz
    jq toy .f<TAB> -> jq toy .foo, ENTER -> print 1

@albertogalan
Copy link

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