3

How can I transform the JSON input

{
"Subnets": [
    {
        "VpcId": "vpc-xxx",
        "Tags": [
            {
                "Value": "staging_subnet_private_a",
                "Key": "Name"
            }
        ],
        "SubnetId": "subnet-xxx"
    },
    ...
    ]
}

to

[
 {
  "SubnetId": "subnet-xxx",
  "Name": "staging_subnet_private_a"
 },
 ...
]

using jq?

I have a working solution using jq '[.Subnets[] | {SubnetId, Name: .Tags[0] | .Value }]', but this relies on the order of Tags (not good).

Could I use from_entires or reduce maybe?

2 Answers 2

5

Yes, you could use from_entries. In jq 1.5rc1 and above, it is defined as taking Key/Value key names as well as key/value.

Try something like:

jq '.Subnets | map({SubnetId} + (.Tags | from_entries))'

On previous versions, you could modify the "entries" before passing them to from_entries:

jq '.Subnets | map({SubnetId} + (.Tags | map({value: .Value, key: .Key}) | from_entries))'

Sign up to request clarification or add additional context in comments.

1 Comment

Depending on the requirements, mapping all tags might include too much. So an additional select call would help limit what's used.
1

Here is a solution which only uses jq primitives.

[
  .Subnets[]
| {SubnetId} + (.Tags[] | if .Key=="Name" then {Name:.Value} else empty end)
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.