简体   繁体   中英

Typesafe Config: How to get list of lists

I have a config file with the following structure:

# ExampleConfig
exampleConfig {
  steps = [
    ["app_one", "step_one", "step_two"],
    ["app_two", "step_one", "step_two"]
  ]
  tags = [
    ["owner", "me"],
    ["env", "prod"],
    ["tenant", "me"]
  ]
}

What I am trying to do is load the config file into the app, and then extract the lists from inside the config file (eg steps, tags). I am a bit stuck on how to do it. I've tried using the following but they do not return my desired results:

val config: Config = ConfigFactory.load(configFile).getConfig(configValue)
val steps = config.getList("steps")

The end result I would like to have is as follows:

val steps: List[(String, String, String)] = List(("app_one", "step_one", "step_two"), ...))
val tags: List[(String, String)] = List(("owner", "me"),("env", "prod"), ...))

In general, the concept of tuples does not exist in json. Therefore, you have to enforce the conversion to a tuple in your application, and not in the json. The implication of the last, is that you cannot write generic code that will convert any number of arguments.

You can try something like:

val config = ConfigFactory.parseString(configString)
val steps = config.getList("steps").asScala.map {
  case internalList: ConfigList =>
    if (internalList.size() != 3) ???
    internalList.asScala.map(_.unwrapped()) match {
      case mutable.Buffer(a1, a2, a3) =>
        (a1, a2, a3)
    }
}.toList

val tags = config.getList("tags").asScala.map {
  case internalList: ConfigList =>
    if (internalList.size() != 2) ???
    internalList.asScala.map(_.unwrapped()) match {
      case mutable.Buffer(a1, a2) =>
        (a1, a2)
    }
}.toList

println(steps)
println(tags)

Code run at Scastie .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM