简体   繁体   English

Typesafe Config:如何获取列表列表

[英]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.一般来说,json中不存在元组的概念。 Therefore, you have to enforce the conversion to a tuple in your application, and not in the json.因此,您必须在应用程序中强制转换为元组,而不是在 json 中。 The implication of the last, is that you cannot write generic code that will convert any number of arguments.最后一点的含义是,您不能编写将转换任意数量的 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 .代码在Scastie运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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