jcazevedo / moultingyaml

Scala wrapper for SnakeYAML

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Extracting something in the path

timgent opened this issue · comments

I have a yaml object which has been parsed successfully and I'm interested in just a couple of the keys. I'd like to be able to specify the paths for the keys and cast them to strings. Is there an easy way to do this? Couldn't see anything in the docs

MoultingYAML doesn't provide that facility. Currently, the best way to achieve that is to define a function on the lines of the following:

def getFromPath(yaml: YamlValue, path: List[String]): Option[String] = {
  path match {
    case Nil => yaml match {
      case YamlString(s) => Some(s)
      case _ => None
    }
    case h :: t => yaml match {
      case YamlObject(fields) => fields.get(YamlString(h)).flatMap(getFromPath(_, t))
      case _ => None
    }
  }
}

val yaml = """
k1:
  k2:
    k3: "test"
  k3: "2"
""".parseYaml

getFromPath(yaml, List("k1")) // returns None
getFromPath(yaml, List("k1", "k2", "k3")) // returns Some("test")
getFromPath(yaml, List("k1", "k3")) // returns Some("2")

However, I have on my backlog the idea to integrate a lens library (probably Monocle) with MoultingYAML, and that would enable an easier definition of extractors from a path.

Thanks @jcazevedo, that's great