scalatypesafehocon

How can I generate typesafe config (Hocon) file dynamically in scala (generate config file)


I want to generate Hocon config dynamically.

Input Map and

output file with below content

block{
key1 : value
key2 : value
}

Trying to read map
     var myMap = new util.HashMap[String,AnyRef]()
     val myConfig = ConfigFactory.parseMap(myMap)

myConfig.toString print below
Config(SimpleConfigObject({"key":"value"}))

not able to figure out how to extract conf from it

I tried below option but it prints in JSON format

val finalConfig : String =
      myConfig.root().render( ConfigRenderOptions.defaults())
println(finalConfig)

Any other approach to generate conf so that nested structure can be supported ?

Edit: Found solution Nested config can be created using ConfigFactory.withValue https://marcinkubala.wordpress.com/2013/10/09/typesafe-config-hocon/


Solution

  • I'm not sure if I'm understanding your problem well...

    But it seems to me, that you only need to format your Map as a HOCON-like String.
    Which you can latter write to a file.

    Hope this code snippet is what you are looking for:

    import collection.JavaConverters._
    
    def toHocon(map: java.util.Map[String, AnyRef]): String =
      map
       .asScala
       .map { case (key, value) => s"$key : $value" }
       .mkString("block{\n\t", "\n\t", "\n}")
    

    (I used one tab character for the indentation, you may replace it with more tabs, or with a fixed number of white spaces).