有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

SnakeYAML scala中的java YAML环境变量插值

利用SnakeYAML&;在scala中,我使用以下方法来解析YAML文件。此方法支持在YAML中使用锚

import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import java.io.{File, FileInputStream}
import org.yaml.snakeyaml.{DumperOptions, LoaderOptions, Yaml}
/**
 * YAML Parser using SnakeYAML & Jackson Implementation
 *
 * @param yamlFilePath : Path to the YAML file that has to be parsed
 * @return: JsonNode of YAML file
 */
def parseYaml(yamlFilePath: String): JsonNode = {
  // Parsing the YAML file with SnakeYAML - since Jackson Parser does not have Anchors and reference support
  val ios = new FileInputStream(new File(yamlFilePath))
  val loaderOptions = new LoaderOptions
  loaderOptions.setAllowDuplicateKeys(false)
  val yaml = new Yaml(
    loaderOptions
  )

  val mapper = new ObjectMapper().registerModules(DefaultScalaModule)
  val yamlObj = yaml.loadAs(ios, classOf[Any])

  // Converting the YAML to Jackson YAML - since it has more flexibility for traversing through nodes
  val jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(yamlObj)
  val jsonObj = mapper.readTree(jsonString)
  println(jsonString)
  jsonObj
}

但是,目前不支持在YAML文件中插入环境变量。如果我们得到以下环境变量

>>> println(System.getenv())
{PATH=/usr/bin:/bin:/usr/sbin:/sbin, XPC_FLAGS=0x0, SHELL=/bin/bash}

问题是我们如何在yaml文件中实现环境变量插值,假设我们有以下yaml文件:

path_value: ${PATH}
xpc: ${XPC_FLAGS}
shell_path: ${SHELL}

然后在解析YAML之后,YAML应该是:

{
   "path_value": "/usr/bin:/bin:/usr/sbin:/sbin",
   "xpc": "0x0",
   "shell_path": "/bin/bash"
}

感谢您的时间和支持;努力提前回答


共 (0) 个答案