微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SnakeYAML scala 中的 YAML 环境变量插值

如何解决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 举报,一经查实,本站将立刻删除。