Home > other >  JQ reshape nested array
JQ reshape nested array

Time:12-11

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?

CodePudding user response:

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

CodePudding user response:

You need to put values in an array :

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