【问题标题】:When using JSON-based config files for Typesafe configuration (instead of HOCON) how to include another file?当使用基于 JSON 的配置文件进行 Typesafe 配置(而不是 HOCON)时,如何包含另一个文件?
【发布时间】:2022-01-10 08:38:46
【问题描述】:

我之前已经成功地将 include 指令与 HOCON 一起使用。 但是,我当前的项目要求我们的配置文件定义在 出于客户指定原因的 JSON。这很好,但我也需要 将这些配置的共同元素分解为单独的“基础” 包含通用定义的配置文件。

我试过语法

{ "include":  "some-common-file.json"}

但这对我来说并不奏效。

示例程序如下所示。查看变量的结果 调试器中的“配置”表明 键“粘贴”具有预期值“猴子”。

但是,还有一个键 'include',其值为 'foo.json'。 foo.json的内容没有带进来。

一定有办法做到这一点(我希望!)
如果您能帮助阐明“如何做”,我将不胜感激!

示例程序

import com.typesafe.config.{Config, ConfigBeanFactory, ConfigFactory}
import com.typesafe.scalalogging.LazyLogging
import org.testng.annotations.Test

class ConfigTest extends LazyLogging {

  @Test def testJson(): Unit = {
    val config: Config = ConfigFactory.load("bar.json")
    System.out.println("config:" + config)
  }
}



// bar.json
{
    "include":  "foo.json",
    "paste": "monkey"
}

// foo.json
{"testRules":
  {
  "foo": "Steve",
  "bar": 30
  }
}

注意:我尝试了建议的答案之一——非常感谢——但它没有成功。即这种方法:

  #include "foo.json",

@newt 推荐——对我来说,结果如下:

bar.json @ file:/project/foo/build/resources/test/bar.json: 2: Expecting close brace } or a field name here, got '#' (Reserved character '#' is not allowed outside quotes)
com.typesafe.config.ConfigException$Parse: bar.json @ file:/project/foo/build/resources/test/bar.json: 2: Expecting close brace } or a field name here, got '#' (Reserved character '#' is not allowed outside quotes)
        at com.typesafe.config.impl.ConfigDocumentParser$ParseContext.parseError(ConfigDocumentParser.java:201)

注2: 这个语法:

  { "include":  "some-common-file.json"}

导致这个错误:

 Token not allowed in valid JSON: 'include'

感谢 newt 对原始答案的修改,但我认为修改后的答案中引用的文档是针对 HOCON 的,而不是针对 Json 的。在这一点上,我会给出我的左腿作为一个很好的工作示例,我将获得赏金。

【问题讨论】:

  • 对不起,我已经更新了我的答案。请尝试并告诉我:)

标签: include configuration-files typesafe-config


【解决方案1】:

HOCON documentation 指定 unquoted 包含后跟文件路径具有特殊含义。

Bar.json:

{ include file("path/to/foo.json")
}

注意:确保 foo.json 中的替换是相对于应用的根配置

【讨论】:

  • 谢谢!我确实尝试过.. 很遗憾没有运气.. 在原始帖子中添加了关于我观察到的结果的注释。
  • 嘿,@newt 再次感谢.. 我尝试了修改后的答案,但没有运气。在原帖中添加了 cmets。
  • 什么错误,能分享一下吗?
  • 嗨..我更新了 cmets w/尝试修改答案的结果。简而言之->“有效JSON中不允许使用令牌:'include'”。我正在重新提出这个问题。如果你能提供一个可行的例子,那就是你的全部了。我衷心感谢。
猜你喜欢
  • 2015-02-26
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 2014-10-07
相关资源
最近更新 更多