Convert HOCON (.conf) to JSON with scala/play?
Asked Answered
B

2

9

I want to convert a .conf-file directly to json so I can pass it to frontend. Is there a way to do that in scala/play? It seems to be incredibly cumbersome with the path I'm taking now:

val conf: Configuration = play.api.Configuration.apply(ConfigFactory.parseFile(new File("app/assets/strings.conf")))
conf.entrySet.seq.map(t => t._1 -> t._2.unwrapped())
// which gives me a Seq[(String, AnyRef)] which cannot be converted with Json, so the path from here is even uglier

I'm tempted to go back to JSON, but the HOCON-syntax is perfect for our use-case. HOCON is basicly JSON with less braces and quotes - so conversion should be very straightforward. Still I can't find a simple way to do anything like it with play/scala.

Badger answered 30/11, 2014 at 11:0 Comment(0)
U
26

This will do:

val config = ConfigFactory.load(); // read Config here 

val configJSON : String = 
  config.root().render( ConfigRenderOptions.concise() )

This will give you a JSON string.

There are additional options how you want the output formatted. More in the documentation: https://typesafehub.github.io/config/latest/api/com/typesafe/config/ConfigValue.html#render()

Undercover answered 30/11, 2014 at 13:5 Comment(1)
NB - if you load("anystringatall") you will not get an error, but a sort of default config, which may confuse you. I was trying to load a HOCON formatted config file from the REPL and ended up using ConfigFactory.parseFile(File) to make sure I am parsing the correct fileQuiteri
S
2

In case anyone comes here wondering how to do the same thing in Java, at least for play 2.2.x you can do the following:

config.underlying().root().render(ConfigRenderOptions.concise());
Screamer answered 28/6, 2016 at 12:21 Comment(1)
to all of those who downvoted, please tell me why so here.. this should be a rule.. thanksSorn

© 2022 - 2024 — McMap. All rights reserved.