Austin H
Austin H

Reputation: 11

Pass bash variable (string) as jq argument to walk JSON object

This is seemingly a very basic question. I am new to JSON, so I am prepared for the incoming facepalm.

I have the following JSON file (test-app-1.json):

"application.name": "test-app-1",
"environments": {
    "development": [
        "server1"
    ],
    "stage": [
        "server2",
        "server3"
    ],
    "production": [
        "server4",
        "server5"
    ]
}

The intent is to use this as a configuration file and reference for input validation.

I am using bash 3.2 and will be using jq 1.4 (not the latest) to read the JSON.

The problem: I need to return all values in the specified JSON array based on an argument.

Example: (how the documentation and other resources show that it should work)

APPLICATION_ENVIRONMENT="developement"

jq --arg appenv "$APPLICATION_ENVIRONMENT" '.environments."$env[]"' test-app-1.json

If executed, this returns null. This should return server1.

Obviously, if I specify text explicitly matching the JSON arrays under environment, it works just fine: jq 'environments.development[]' test-app-1.json returns: server1.

Limitations: I am stuck to jq 1.4 for this project. I have tried the same actions in 1.5 on a different machine with the same null results.

What am I doing wrong here?

jq documentation: https://stedolan.github.io/jq/manual/

Upvotes: 0

Views: 1345

Answers (1)

randomir
randomir

Reputation: 18697

You have three issues - two typos and one jq filter usage issue:

  • set APPLICATION_ENVIRONMENT to development instead of developement
  • use variable name consistently: if you define appenv, use $appenv, not $env
  • address with .environments[$appenv]

When fixed, looks like this:

$ APPLICATION_ENVIRONMENT="development"
$ jq --arg appenv "$APPLICATION_ENVIRONMENT" '.environments[$appenv][]' test-app-1.json
"server1"

Upvotes: 1

Related Questions