skip to Main Content

Im using ubuntu to store JSON-encoded text into a environment variable like this:

~ test='{"test": { "mmm":"432"}}'
~ echo $test
{"test": { "mmm":"432"}}

how can i access the key "test" to print {"mmm":"432"}?

something like

~ test='{"test": { "mmm":"432"}}'
~ echo $test.test
{ "mmm":"432"}

3

Answers


  1. Bash doesn’t have json support. You must use a command line jq to process the output.

    For example:

    echo "$test" | jq .test

    Login or Signup to reply.
  2. https://jqlang.github.io/jq/ is your friend.

    Simply use echo "$test" | jq .test.

    Login or Signup to reply.
  3. If $test is really an (exported) "environment variable", you can use jq’s env or $ENV builtins to access it, avoiding the echo subshell:

    jq -n 'env.test | fromjson.test'
    # or
    jq -n '$ENV.test | fromjson.test'
    # or
    jq -n 'env["test"] | fromjson.test'
    # or
    jq -n '$ENV["test"] | fromjson.test'
    
    {
      "mmm": "432"
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search