jq - print values in one line

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

$ 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).

Tags:

Json

Jq