Jq – print values in one line

jqjson

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.

Best Answer

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: -
Related Question