DEV Community

ques0942
ques0942

Posted on

2

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)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay