Ashwin
Ashwin

Reputation: 13527

Substituting key with environment variable in HOCON

I am using pureconfig to read config for my Scala application. The application.conf file is in HOCON format. My config file looks something like this

weathers {
    ${?HUMID_WEATHER_ID} {
      temperature = 10
      temperature = ${?HUMID_WEATHER_TEMPERATURR}
    }
    ${?HOT_WEATHER_ID} {
      temperature = 10
      temperature = ${?HOT_WEATHER_TEMPERATURR}
    }
}

weathers is a map whose keys should be substituted by the environment variables HUMID_WEATHER_ID and HOT_WEATHER_ID. But when I read the config I get this exception

 135) Unable to parse the configuration: expecting a close parentheses ')' here, not: '${'HUMID_WEATHER_ID'}'.

The substitutions work fine in values but not in Keys. Is this intended? Is there a way to get around this?

Upvotes: 1

Views: 910

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191733

Rather than use an ID for a key, might I suggest a static name such as hot and humid? Each element then has an id field that can be substituted.

weathers {
    humid {
      id = ${?HUMID_WEATHER_ID} {
      temperature = 10
      temperature = ${?HUMID_WEATHER_TEMPERATURR}
    }
    hot {
      id = ${?HOT_WEATHER_ID}
      temperature = 10
      temperature = ${?HOT_WEATHER_TEMPERATURR}
    }
}

Then change your code to do interpolation on the name rather than a numeric string

val weather = "humid"
val id = config.get(s"weathers.$weather.id")

Upvotes: 0

Related Questions