Search code examples
javascalahocon

Dynamic keys in hocon


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'.


Solution

  • 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)