11

json input:

[
  {
    "name": "cust1",
    "grp": [
      {
        "id": "46",
        "name": "BA2"
      },
      {
        "id": "36",
        "name": "GA1"
      },
      {
        "id": "47",
        "name": "NA1"
      },
      {
        "id": "37",
        "name": "TR3"
      },
      {
        "id": "38",
        "name": "TS1"
      }
    ]
  }
]

expected, on output are two lines:

name: cust1
groups: BA2 GA1 NA1 TR3 TS1

I was trying to build filter without success..

$ jq -r '.[]|"name:", .name, "groups:", (.grp[]|[.name]|@tsv)' test_json
name:
cust1
groups:
BA2
GA1
NA1
TR3
TS1

Update: the solution provided below works fine, but I did not predict case when no groups exists:

[
  {
    "name": "cust1",
    "grp": null
  }
]

in such case, the solution provided returns error:

$ jq -jr '.[]|"name:", " ",.name, "\n","groups:", (.grp[]|" ",.name),"\n"' test_json2
name: cust1
jq: error (at test_json2:6): Cannot iterate over null (null)

any workaround appreciated.

17

Use the "join", -j

$ jq -jr '.[]|"name:", " ",.name, "\n","groups:", (.grp[]|" ",.name),"\n"' test_json
name: cust1
groups: BA2 GA1 NA1 TR3 TS1

And with a place holder

$ jq -jr '.[]|"name:", " ",.name, "\n","groups:", (.grp//[{"name":"-"}]|.[]|" ",.name),"\n"' test_json
name: cust1
groups: -
2
  • is it possible to print "-" in case no group names exists in json? I've tried (.grp[]|" ",.name) // "-","\n" but get error Cannot iterate over null (null) – Chris Jun 23 '18 at 20:45
  • 2
    I think you don't need the -r switch, when already using -j. JQ's man: --join-output / -j: Like -r but jq won't print a newline after each output. – Tomasz Gandor Jan 29 at 21:35
4
$ jq -r '.[] |
      [ "name:", .name ], [ "groups:", .grp[].name ]
      | @tsv' file.json
name:   cust1
groups: BA2     GA1     NA1     TR3     TS1

That is, give @tsv two arrays, one with the name, and one with the groups. Each array will become its own row.

In case the grp array may be empty and you'd like to insert a - instead:

$ jq -r '.[] |
      [ "name:", .name ], [ "groups:", (.grp // [])[].name // "-" ]
      | @tsv' file.json
name:   cust1
groups: -

The operation x // y returns x unless x evaluates to null or false in which case it returns y.

This will also handle the case where grp is completely missing (not just an empty array).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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