1

Let's say I have config like this:

root {
  value1: 1
  value2: 2

  values {
     dynamic1 {
        static1: 10
        static2: "test"
     }
     dynamic2 {
        static1: 10
        static2: "test"
     }
  }
}

Is it possible and how to get collection (map perhaps?) of sub-elements of root.values element, when they have dynamic name?

I've found method Config.getConfigList but it doesn't provide the name of 'subconfigs'.

Matej Kormuth
  • 2,139
  • 3
  • 35
  • 52

2 Answers2

2

try this:

// Map[String,String]
val values = node.root().keySet.asScala map (id => 
  id -> node.getString(id)
) toMap

Explanation: You can't query for a map of values (not sure why), but you can obtain a list of keys from a ConfigObject by calling node.root().keySet.asScala. Then you can use those keys to use any of the existing methods, like getString, getConfig, etc.

Alvaro Carrasco
  • 6,103
  • 16
  • 24
  • Please add some explanation. Imparting the underlying logic is more important than just giving the code, because it helps the OP and other readers fix this and similar issues themselves. – Jeen Broekstra Dec 08 '15 at 23:25
1

There is a lot of confusion because each Config has a root (the root of the whole object), but the top of your hierarcy is also called root, and we are talking about two different roots. Here is scala shell excerpt which illustrates what is going on:

  • cfig is of type Config
  • cfig.root() is of type ConfigObject, where you can iterate over children, and where you can invoke entrySet and also keySet. In your case, the only child is of cfig.root() is root, which is the top of your hierarchy
  • cfig.getObject("root") is of type ConfigObject, but its children are children one level below the top of your hierarchy - value1, value2, values

    scala> cfig
    

res75: com.typesafe.config.Config = Config(SimpleConfigObject({"root":{"value1":1,"value2":2,"values":{"dynamic1":{"static1":10,"static2":"test"},"dynamic2":{"static1":10,"static2":"test"}}}}))

scala> cfig.root()
res74: com.typesafe.config.ConfigObject = SimpleConfigObject({"root":{"value1":1,"value2":2,"values":{"dynamic1":{"static1":10,"static2":"test"},"dynamic2":{"static1":10,"static2":"test"}}}})

scala> val c2 = cfig.getObject("root")
c2: com.typesafe.config.ConfigObject = SimpleConfigObject({"value1":1,"value2":2,"values":{"dynamic1":{"static1":10,"static2":"test"},"dynamic2":{"static1":10,"static2":"test"}}})

scala> c2.entrySet.size
res72: Int = 3

scala> c2.keySet.toSet
res73: scala.collection.immutable.Set[String] = Set(value2, value1, values)
KrisP
  • 1,206
  • 8
  • 10