3

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
  • 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 at 12:48
  • 1
    .[] | (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 at 16:42
11

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.

  • 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 at 14:01

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.