0

I'm new to jq, I have the following JSON & I need to extract FOUR values i.e. SAUCE_KEY, sauceKey, SAUCE_VALUE, sauceValue etc. And I need to covert these bash variables as i.e.

SAUCE_KEY=sauceKey
SAUCE_VALUE=sauceValue

If I will echo it, it should print it's value ie. echo $SAUCE_KEY

I have used the code as:

jq -r '.env_vars[] | with_entries(select([.key] | inside([".env_vars[].name", ".env_vars[].value"])))' | jq -r "to_entries|map(\"\(.value)=\(.value|tostring)\")|.[]"

By doing so, i was able to get values as name=SAUCE_KEY, value=sauceKey and so on.

{
  "@type": "env_vars",
  "env_vars": [
    {
      "@type": "env_var",
      "@href": "/repo/xxxxx/env_var/xxxxx",
      "@representation": "standard",
      "@permissions": {
        "read": true,
        "write": true
      },
      "name": "SAUCE_KEY",
      "value": "sauceKey"
    },
    {
      "@type": "env_var",
      "@href": "/repo/xxxxx/env_var/xxxxx",
      "@representation": "standard",
      "@permissions": {
        "read": true,
        "write": true
      },
      "name": "SAUCE_VALUE",
      "value": "sauceValue"
    }
  ]
}
1

1 Answer 1

2

If instead of trying to extract variable names from the JSON, you populate an associate array with the names as keys, it's pretty straightforward.

#!/usr/bin/env bash

declare -A sauces
while IFS=$'\001' read -r name value; do
    sauces[$name]=$value
done < <(jq -r '.env_vars[] | "\(.name)\u0001\(.value)"' saucy.json)

for name in "${!sauces[@]}"; do
    echo "$name is ${sauces[$name]}"
done

prints out

SAUCE_VALUE is sauceValue
SAUCE_KEY is sauceKey
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, after your answer i guess i'm just one step away from final solution, can you please clarify on the followings: 1. JSON that pasted above in my question, get it from Curl response in bash then saved into var but let me know how can I save it to json file i.e. saucy.json 2. Facing the issues: * env-var.sh: 14: env-var.sh: declare: not found (I guess for "declare -A sauces") * env-var.sh: 17: env-var.sh: Syntax error: redirection unexpected (I guess due to symbol as "< <")
@AbidRana Sounds like you're not using bash, or maybe a really old version.
Oh, and curl whatever > saucy.json. Or avoid a file and feed curl's JSON output directly to jq: curl whatever | jq -r 'whatever'
You recommended solution works perfactly well on my win10 (GNU bash, version 4.4.19(2)-release (x86_64-pc-msys)). I'm just wondering, if you know how can I have updated/same version in Tracis ci?

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.