Skip to content

Instantly share code, notes, and snippets.

@albertogalan
Created July 18, 2020 08:34
Show Gist options
  • Save albertogalan/957a11d15c385c07d0be219a3fbf984c to your computer and use it in GitHub Desktop.
Save albertogalan/957a11d15c385c07d0be219a3fbf984c to your computer and use it in GitHub Desktop.
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 'paths | map(.|tostring)|join(".")' $prev | tr -d '"' | sed 's=^=\.=')
COMPREPLY=( $(compgen -W "$keys" -- $curr ) )
;;
esac
}
complete -F _jq jq
@Cyb3rN8
Copy link

Cyb3rN8 commented Sep 19, 2023

Wow Thanks! This is inspiring! I make some adjustment to fit my need along with bug fixes:

It' also ported to ZSH

local KNOWLEDGEBASE_FILE=~/knowledge-base.yml

function kb() {

  # BUGFIX: Split json_path by `.` and surround each part with double quotes
  local json_path=$1 
  json_path=(${json_path//./"\".\""})
  json_path="\"${json_path[@]}\""
  
  yq $KNOWLEDGEBASE_FILE -o=json | jq ".$json_path"
}

#autoload
_kb() {
  local state
  local -a matches
  local -a json_paths
  
  # ENHANCEMENT: add `(type != "object") so it only suggest leave node path to avoid redundancies
  json_paths=($(yq $KNOWLEDGEBASE_FILE -o=json | jq -c 'paths(type != "object")|map(.|tostring)|join(".")' | tr -d '"'))
  matches=("${json_paths[@]}")
  
  _arguments '1: :->key'
  case $state in
    key)
        _describe 'key' matches
    ;;
  esac
  
  return 0
}

autoload -Uz compinit && compinit
compdef _kb kb

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