24

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.

2 Answers 2

30

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) Commented Jun 23, 2018 at 20:45
  • 3
    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. Commented Jan 29, 2021 at 21:35
6
$ 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).

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.