Typesafe config: get as map

Viewed 7829
googlesheets{
 dmkb_sheet = "1xEC8CPlKn654321wcoS_JB12345cPPiaA0M"
 other_sheet = "123isS0M30TH3R1D"
}

I would like to use something like myConfig.getAsMap("googlesheets") and get the two nested entries as a Map. No such method exists. So what is the easiest way to load the two nested entries as a Map?

4 Answers

For some definition of easy you could use something like this:

val config = conf.atKey("googlesheets")
config.root.keySet.asScala.map(key ⇒ key → config.getString(key)).toMap

I would argue that it would be even easier to use a library for mapping configurations to case classes, like pureconfig

OK, that was easy.

myConfig.getConfig("googlesheets").entrySet() does the trick

(I was fixated on the method having a "get" prefix, so missed it)

Thanks. I got it working by re-writing your answer as follows:

config.entrySet().asScala.map(e => e.getKey -> e.getValue.render()).toMap

I was after a scala Map[String, String] @Senthil's answer came closest to what I was after but the Map values were quoted i.e. they were enclosed in double quotes and that caused a nasty bug which was not easy to spot. The way I was able to resolve it is by doing configValue.unwrapped().toString() rather than configValue.render()

Before this I tried render() with various ConfigRenderOptions but I did not get the desired result

config
    .getConfig("<key>")
    .entrySet()
    .asScala
    .map(e => e.getKey -> e.getValue.unwrapped().toString)
    .toMap

I am using this in scala and therefore convert it to scala type

Alas, typesafe config which is otherwise a cool library had to make config as Map so hard!

Related