How to define an object as environment variable with hocon config

653 views Asked by At

What I want to do

Defining a base set of objects which can be enhanced by an environment variable. In the following you see a little example of my hocon config file so far.

foo.bar-base= [
  {a: "hello", b: "world"},
  {a: "hello", b: "stackoverflow"}
]
foo.bar-extended = ${?EXTENDED}
foo.bar = ${foo.bar-base} ${foo.bar-extended}

The Problem

When trying to define elements to add as environment variables I get the exception that states that foo.bar has type list of STRING rather than list of OBJECT.

Is there any way to make the value of the environment variable be parsed as object?

EXTENDED.0={a:"hello", b:"rest"}
1

There are 1 answers

0
Yannic Bürgmann On

I used a workaround. Instead of using config.getConfigList which directly returns a list of Config objects, I used config.getList which returns a List of ConfigValues.

Then I did the parsing manually:

final ConfigList list = config.getList("foo.bar");
final Stream<Config> configsFromString = list.stream()
                    .filter(value -> ConfigValueType.STRING.equals(value.valueType()))
                    .map(ConfigValue::unwrapped)
                    .map(Object::toString)
                    .map(ConfigFactory::parseString);
final Stream<Config> configsFromMap = list.stream()
                    .filter(value -> ConfigValueType.OBJECT.equals(value.valueType()))
                    .map(ConfigValue::render)
                    .map(ConfigFactory::parseString);
final List<Config> configs = Stream.concat(configsFromString, configsFromMap)
                    .collect(Collectors.toList());