DEV Community

ques0942
ques0942

Posted on

jq sample(definition syntax for variable and function)

jq

use query string from a file

you can write query at a file like below.

curl "http://localhost:8080/" | jq -f jq_query

variable definition

echo '{"a": "valueA"}' |\
  jq '. | {"b": "valueB"} as $v | {"a2": .a, "b2": $v.b}'
# output
# {
#  "a2": "valueA",
#  "b2": "valueB"
#}

function definition and if statement

echo '[{"a": "valueA"}, {"b": "valueB"}]' |  jq '[.[] | 
    def replace(d): d as $d | 
      if (.a == null and .b != null) then {"a": $d.a, "b": .b}
      elif (.a != null and .b == null) then {"a": .a, "b": $d.b}
      elif (.a == null and .b == null) then {"a": $d.a, "b": $d.b}
      else {"a": .a, "b": .b}
      end;
    replace({"a": "valueA2", "b": "valueB2"})]'
# output
#[
#  {
#    "a": "valueA",
#    "b": "valueB2"
#  },
#  {
#    "a": "valueA2",
#    "b": "valueB"
#  }
#]

Top comments (0)