rascio
rascio

Reputation: 9279

JQ reshape nested array

I have an issue with jq and nested arrays, I cannot get why it is creating multiple objects:

echo '{
    "first": [
        {
            "second": {
                "id": 1,
                "third": [
                    {
                        "value": "aa"
                    },
                    {
                        "value": "bb"
                    }
                ]
            }
        }
    ]
}' | jq '.first[].second | {id: .id, prop: .third[].value}'

This is returning:

{
  "id": 1,
  "prop": "aa"
}
{
  "id": 1,
  "prop": "bb"
}

But I would like to have:

{
  "id": 1,
  "prop": ["aa", "bb"]
}

What am I missing?

Upvotes: 1

Views: 322

Answers (2)

pmf
pmf

Reputation: 36033

Use the map builtin to transform the array into just .values:

jq '.first[].second | {id: .id, prop: .third | map(.value)}'
{
  "id": 1,
  "prop": [
    "aa",
    "bb"
  ]
}

Demo

Upvotes: 1

Philippe
Philippe

Reputation: 26437

You need to put values in an array :

jq '.first[].second | {id: .id, prop: [.third[].value]}'

Upvotes: 0

Related Questions