jq

nicolaw 30th July 2020 at 2:33pm
Bash JSON

Examples

$ jq -r -e '.scripts|if ."test:xunit" != null then "test:xunit" elif .test != null then "test" else empty end' package.json

Get the latest database release download URL from the TrinityCore GitHub repository:

#!/usr/bin/env bash

set -euo pipefail

get_tdb_url() {
  declare tag="${1:-TDB}"
  # https://developer.github.com/v3/
  # https://github.com/TrinityCore/TrinityCore/releases
  curl -sSL ${GITHUB_USER:+"-u$GITHUB_USER:$GITHUB_PASS"} \
    "${GITHUB_API}/repos/${GITHUB_REPO}/releases" \
    | jq -r "\"tdb_url=\" + ( [
                .[] | select(
                .tag_name | contains( \"$tag\" ) )
                .assets[] .browser_download_url
              ] | max )"
}

main() {
  declare GITHUB_USER="${GITHUB_USER:-}"
  declare GITHUB_PASS="${GITHUB_PASS:-}"
  declare GITHUB_API="https://api.github.com"
  declare GITHUB_REPO="trinitycore/trinitycore"

  declare $(get_tdb_url TDB335)
  echo "$tdb_url"
}
 
main "$@"

Bash Structures into JSON

The following StackOverflow has a few very useful snippets of code in it: https://stackoverflow.com/questions/44792241/constructing-a-json-hash-from-a-bash-associative-array

$ printf 'one first two second three third' | jq -Rs '
  split(" ")
  | . as $a
  | reduce range(0; length/2) as $i 
      ({}; . + {($a[2*$i]): ($a[2*$i + 1]|fromjson? // .)})'
{
  "one": "first",
  "two": "second",
  "three": "third"
}
for i in "${!dict[@]}"
do
    echo "\"$i\""
    echo "${dict[$i]}"
done | 
jq -n 'reduce inputs as $i ({}; . + { ($i): input })'
printf "%s" "$i" | jq -Rs .
for i in "${!dict[@]}"
do
    echo "$i" 
    echo "${dict[$i]}"
done |
jq -n -R 'reduce inputs as $i ({}; . + { ($i): (input|(tonumber? // .)) })'
declare -A dict=( [$'foo\naha']=$'a\nb' [bar]=2 [baz]=$'{"x":0}' )

for key in "${!dict[@]}"; do
    printf '%s\0%s\0' "$key" "${dict[$key]}"
done |
jq -Rs '
  split("\u0000")
  | . as $a
  | reduce range(0; length/2) as $i 
      ({}; . + {($a[2*$i]): ($a[2*$i + 1]|fromjson? // .)})'
find . -mindepth 2 -maxdepth 2 -name package.json -exec \
  jq -r --arg file "{}" \
  'select(.scripts."test:jenkins" != null)|$file|split("/")|.[1]' "{}" \;

Related