5

I need to display users if their realm is internal.

Input:

[
  {
    "name": "A_A",
    "uri": "https:test/test",
    "realm": "internal"
  },
  {
    "name": "B_B",
    "uri": "https:test/test",
    "realm": "internal"
  },
  {
    "name": "C_C",
    "uri": "https:test/test",
    "realm": "external"
  }
]

Tried with:

jq 'if .[].realm == "internal" then .[].name else empty end'

But the problem is that it is listing all the users.

Expected output:

A_A , B_B
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • I would look at the Elastic search syntax, if you are talking to one. I am not exactly on expert on that, I often do my queries though trial and error, so not the best person to write an answer. – Rui F Ribeiro Feb 19 '19 at 12:48
  • 3
    .[] | (if .realm == "internal" then .name else empty end). You have to put your conditional after you iterated into the individual item you want to test. – Charles Duffy Feb 19 '19 at 16:42

3 Answers3

19

You can use the jq function select:

<file jq -r '.[] | select(.realm == "internal") | .name'

The first .[] gets the array elements. The select() applies to individual element and filter the ones have the correct realm. The last part prints the name field.

oliv
  • 2,636
  • 1
    If you'd rather have an array, use map(select(.realm == "internal") | .name) instead. That would let you | join(delim) with a specific delimiter if you need to : here's a sample with your exact expected output – Aaron Feb 19 '19 at 14:01
1

You have to put your conditional after you iterated into the individual item you want to test.

jq '.[]| (if .realm == "internal" then .name else empty end)'
αғsнιη
  • 41,407
0

It appears that the user wants CSV formatted output, so I'm just giving an alternative solution that shows how you may do that with the @csv output operator in jq.

This command also uses map() to apply the select() statement to each of the elements of the input array.

$ jq -r 'map(select(.realm == "internal").name)|@csv' file
"A_A","B_B"

This shows that I have approached the issue by selecting the relevant array entries based on the realm key's value and then extracting the value of the name key from these. This leaves us with an array of name values, which @csv formats and outputs as a single CSV record.

Kusalananda
  • 333,661