jq - Use argument to construct a selector

Viewed 3039

I'm wondering if possible to use an argument to construct a field name in jq.

Example:

jq -rc \
   --arg secret_name ${secret_name} \
   --arg secret_value ${secret_value} \
   '.data.$secret_name = "$secret_value"'

In above example, I want to use value of argument secret_name to create a key under .data. Is this possible using jq?

Example Data:

secret_name=abc  
secret_value=xyz 

JSON on which jq is run:

{
    "apiVersion": "v1",
    "data": {},
    "kind": "Secret",
    "metadata": {
        "name": "kv-secrets",
        "namespace": "default"
    },
    "type": "Opaque"
} 

Expected output:

{
    "apiVersion": "v1",
    "data": {
      "abc": "xyz"
    },
    "kind": "Secret",
    "metadata": {
        "name": "secrets"
    },
    "type": "Opaque"
}

Do mind that I intend to run the original command to fill .data will more key-value pairs.

1 Answers
Related