Olki
Olki

Reputation: 35

jq transform - json child array to delimited string

i want to transform the following input with jq

{
    "count": 1000,
    "rows": [{
            "id": 1,
            "child_id": 11,
            "childarray": ["value1", "value2"]
        },
        {
            "id": 2,
            "child_id": 12,
            "childarray": ["value3", "value4"]
        }
    ]
}

Output should be:

[
  {
    "id": 1,
    "child_id": 11,
    "childarray": "value1, value2"
  },
  {
    "id": 2,
    "child_id": 12,
    "childarray": "value3, value4"
  }
]

I use this jq filter-> "[.rows[]]" but don't know howto "join" the array -> "childarray": ["value1", "value2"] to a comma delimited string -> "value1, value2"

https://jqplay.org/s/5TlSDgJnkc

Upvotes: 2

Views: 150

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

map + join approach:

jq '.rows | map(.childarray |= join(", "))' input.json

The output:

[
  {
    "id": 1,
    "child_id": 11,
    "childarray": "value1, value2"
  },
  {
    "id": 2,
    "child_id": 12,
    "childarray": "value3, value4"
  }
]

Another alternative is:

jq '.rows[].childarray |= join(", ") | .rows'

Upvotes: 2

Related Questions