'JSON Array Literal to Object using JQ

I am using an AWS CLI command with json output and it creates an array:

aws lambda list-functions --region us-east-2 --query 'Functions[?starts_with(FunctionName, `DEV`) == `true`].FunctionName' --output json

Which returns:

[
    "DEV-Lambda1-xxxx",
    "DEV-Lambda2-xxxx",
    "DEV-Lambda3-xxxx",
    "DEV-Lambda4-xxxx"
]

In order to properly use the output in my Terraform, I need it to be a JSON object. Here is a simplified example:

{
"lambda1": "DEV-Lambda1-xxxx",
"lambda2": "DEV-Lambda2-xxxx",
"lambda3": "DEV-Lambda3-xxxx",
"lambda4": "DEV-Lambda4-xxxx"
}

I would like to use jq 1.5 or greater. How do I transpose an array into an object?

I've only been able to make it this far:

map( { ("lambda"): . } ) | add 

Which outputs only the last lambda:

{
  "lambda": "DEV-Lambda4-xxxx"
}


Solution 1:[1]

You could do a range iteration over the array and form the desired k/v pair

jq '[ range(0; length) as $r | 
  { ( .[$r] | split("-")[1] | ascii_downcase) : .[$r] } ] | add'

jqplay - demo(1)

or do a transposition of the array and form the k/v pair

jq --slurp 'transpose | 
  map( { ( .[] | split("-")[1] | ascii_downcase) : .[] } ) | add'

jqplay - demo(2)

Solution 2:[2]

Another approach could be to use to_entries | map(…) | from_entries, or its shortcut with_entries(…).

Then change the key based either on a static string and the numeric index:

jq 'with_entries(.key |= "lambda\(.+1)")'

Demo

Or on the lower case version of the middle part of the value:

jq 'with_entries(.key = ((.value / "-")[1] | ascii_downcase))'

Demo

{
  "lambda1": "DEV-Lambda1-xxxx",
  "lambda2": "DEV-Lambda2-xxxx",
  "lambda3": "DEV-Lambda3-xxxx",
  "lambda4": "DEV-Lambda4-xxxx"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2