David Martin
David Martin

Reputation: 347

jq parsing json input with variables

I have this input:

{
  "users": [
    {
      "name": "tester-01",
      "user": {
        "username": "tester01"
      }
    },
    {
      "name": "tester-02",
      "user": {
        "username": "tester02"
      }
    }
  ],
  "current-user": "tester-02"
}

Using jq (1.5), I want to print the username that matches current-user.

Can anyone share how this would be done or tips to get me started?

Upvotes: 0

Views: 414

Answers (2)

jq170727
jq170727

Reputation: 14655

The select solution is good. Here is an alternative that uses foreach.

foreach .users[] as $u (
     ."current-user"
   ; .
   ; if . == $u.name then $u.user.username else empty end
)

Upvotes: 0

David Martin
David Martin

Reputation: 347

This was my solution.

cat 99 | jq -r '."current-user" as $foo | .users[] | select(.name == $foo).user'
{
  "username": "tester02"
}

Upvotes: 2

Related Questions