SnakeYAML scala 中的 YAML 环境变量插值

问题描述

利用 SnakeYAML 和 Jackson 在 Scala 中的最佳优势,我使用以下方法来解析 YAML 文件。该方法支持YAML中anchors的使用

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后应该是:

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

感谢您抽出时间和精力提前回答!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)