2

I am running a command that is pulling json from kubectl and I need to take that json and input it into another json array.

Currently, my command looks like this

kubectl get ingress -o json | jq --arg context "$i" '{"$context":[{namespace: .items[].metadata.namespace, host: .items[].spec.rules[].host}]}'

but my json response is the following -

{
  "$context": [
    {
      "namespace": "test",
      "host": "test.test.com"
    }
  ]
}

I essentially want my json output to resolve the $context variable to include the value from bash variable $i, not the string "$context". Thank you for any help!

2
  • 1
    Could you post an example of your kubectl get ingress -o json command in your question ? Dec 12, 2022 at 20:20
  • Don't put double-quotes around $context in the jq expression -- they make it a literal string rather than a variable reference. (Note: bash expands $variable inside double-quoted strings, but jq doesn't.) Dec 12, 2022 at 20:28

1 Answer 1

0

When constructing an object in jq, the key, if it's not "identifier-like", must be enclosed in parentheses:

$ cat file
{"items":[{"metadata":{"namespace":"test"}, "spec":{"rules":[{"host":"test.test.com"}]}}]}

$ jq --arg context "foo" '{($context): [{namespace: .items[].metadata.namespace, host: .items[].spec.rules[].host}]}' file
# .........................^........^
{
  "foo": [
    {
      "namespace": "test",
      "host": "test.test.com"
    }
  ]
}

"identifier-like" == "composed of alphanumeric characters and underscore, and not started with a digit"

1
  • 1
    Alternatively, .[$context] = {...}
    – Kusalananda
    Oct 30, 2023 at 13:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .