3

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/

user2895589
  • 1,010
  • 4
  • 20
  • 33

3 Answers3

2

You can use kxbmap/configs

This supports play-json out of the box. I use it to map whole configurations directly to case classes.

So your example would look like:

import com.typesafe.config.ConfigFactory
import configs.Configs

val config = ConfigFactory.parseString("""
  block{
    key1 : value
    key2 : value
  }
  """)

config.get[Map[String, String]("block")
pme
  • 14,156
  • 3
  • 52
  • 95
1

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

  • I like this solution but it may not support nested Hocon creation. Any inputs if I want to create nested json in scala like p1{key: value , c1{key1 : value1}} – user2895589 Feb 13 '19 at 01:41
  • 1
    @user2895589 Thanks for accepting my answer, but I really do not answered your question. You should add your own answer and accept that one instead. – Luis Miguel Mejía Suárez Feb 13 '19 at 12:21
1

You can try below :

    myConfig.root().render(com.typesafe.config.ConfigRenderOptions.concise())
Manish
  • 133
  • 2
  • 8