0

I want to do this:

ENV=development cat dbconfig.json | jq '.database.$ENV'

where config looks like:

{
  "database": {
    "development": {
      "name": "example",
      "user": "user",
      "password": "asdfasdf"
    }
  }
}

I want to specify the ENV in the command and use it to fetch the key "development" from the json.

In a makefile specifically, I would like to do:

    # ensure env is set
    ifeq ($(ENV),)
        $(error ENV is not set)
    endif

    CONFIG := $(shell cat config.json)
    DATABASE_NAME = $(shell echo CONFIG | jq 'database.$(ENV).name')

    migrate:
        @migrate -source backend/migrations -database postgres://localhost:5432/$(DATABASE_NAME) up
    .PHONY: migrate

I am new to jq, and somewhat to makefiles, how could this be accomplished?

peak
  • 105,803
  • 17
  • 152
  • 177
Lance
  • 75,200
  • 93
  • 289
  • 503
  • 1
    Does this answer your question? [passing arguments to jq filter](https://stackoverflow.com/questions/34745451/passing-arguments-to-jq-filter) – Inian Jul 16 '21 at 07:22
  • ENV is a special variable in jq-1.6 (atleast). Consider using a different name – Inian Jul 16 '21 at 07:24
  • Replace `DATABASE_NAME = $(shell echo CONFIG...` by `DATABASE_NAME = $(shell echo $(CONFIG)...`. And have a look maybe at a quick intro to make. Note that you could simply `DATABASE_NAME = $(shell cat config.json | jq 'database.$(ENV).name')`. – Renaud Pacalet Jul 16 '21 at 07:45

1 Answers1

0

Using a shell variable may not be the best idea, but if that's what you want, this should give you the hint you're looking for:

ENV=development jq -n 'env.ENV'

Using this approach, though, you'd have to provide the filename as an argument to jq.

Notice that using this approach avoids any conflict with jq's "$-variables".

peak
  • 105,803
  • 17
  • 152
  • 177