Firmin Martin
Firmin Martin

Reputation: 308

jq: join string array whether it is empty or not

I have a JSON test.json as follows:

[
  {
    "a": "a",
    "b": [
      "a",
      "b",
      "c"
    ]
  },
  {
    "a": "a"
  }
]

And I would want to join the field b of each entry and handle the case of its emptiness:

{  "a": "a",
  "b": "a, b, c"
},
{
  "a": "a",
  "b": null
}

The following command works...

cat test.json | 
      jq '.[] | .b as $t | if $t then {a: .a, b: $t | join(", ")} else {a: .a, b: $t} end'

... but it's too long as I have to write almost the same constructor two times.

I have tried to move the if-then-else conditional or even the // operator in the {} construction, but they result to a syntax error.

Upvotes: 1

Views: 1547

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134511

Depending on how you want to handle null/empty values you could try these:

map(.b |= (. // [] | join(", ")))

map(if .b then .b |= join(", ") else . end)

Upvotes: 2

Related Questions