Ben Chuanlong Du's Blog

It is never too late to learn.

Use SnakeYaml in Scala

SnakeYAML

moultingyaml: Scala wrapper for SnakeYAML

Comment

If the input YAML doc has multiple formats, you can first load it as an Object and then use Object.isInstanceOf to check its type and use Object.asInstanceOf[SomeType] to cast it to the right type.

In [1]:
%%classpath add mvn
org.yaml snakeyaml 1.25
In [11]:
import scala.collection.JavaConverters._
Out[11]:
import scala.collection.JavaConverters._
In [2]:
import org.yaml.snakeyaml.Yaml
Out[2]:
import org.yaml.snakeyaml.Yaml
In [3]:
import scala.collection.JavaConverters._
Out[3]:
import scala.collection.JavaConverters._
In [4]:
val yaml = new Yaml()
Out[4]:
Yaml:1842984473
In [5]:
val document = "\n- Hesperiidae\n- Papilionidae\n- Apatelodidae\n- Epiplemidae"
Out[5]:
- Hesperiidae
- Papilionidae
- Apatelodidae
- Epiplemidae
In [6]:
val obj = yaml.load(document).asInstanceOf[java.lang.Object]
Out[6]:
[Hesperiidae, Papilionidae, Apatelodidae, Epiplemidae]
In [7]:
obj.isInstanceOf[java.util.List[String]]
Out[7]:
true
In [12]:
obj.isInstanceOf[Seq[String]]
Out[12]:
false
In [9]:
obj.asInstanceOf[java.util.List[String]]
Out[9]:
[Hesperiidae, Papilionidae, Apatelodidae, Epiplemidae]
In [15]:
obj.asInstanceOf[java.util.List[String]]
Out[15]:
[Hesperiidae, Papilionidae, Apatelodidae, Epiplemidae]
In [13]:
obj.asInstanceOf[Seq[String]]
java.lang.ClassCastException: java.util.ArrayList cannot be cast to scala.collection.Seq
  ... 48 elided
In [30]:
val list = yaml.load(document).asInstanceOf[java.util.List[String]]
Out[30]:
[Hesperiidae, Papilionidae, Apatelodidae, Epiplemidae]
In [12]:
list
Out[12]:
[Hesperiidae, Papilionidae, Apatelodidae, Epiplemidae]
In [15]:
val doc = """
    |aa:
    |  - x
    |  - y
    |bb: z
""".stripMargin
Out[15]:
aa:
  - x
  - y
bb: z
In [16]:
yaml.load(doc).asInstanceOf[java.util.Map[String, Any]]

Read YAML From a File

The following way of reading from a file is problematic ...

In [21]:
import java.io.{File, FileInputStream}
import org.yaml.snakeyaml.Yaml

val inputStream = new FileInputStream(new File("test.yaml"))
val yaml = new Yaml()
Out[21]:
Yaml:923704732
In [23]:
yaml.load(inputStream).asInstanceOf[java.util.Map[String, Any]]

Cast to Map

In [36]:
104.62 / 8
Out[36]:
13.0775
In [ ]:

Comments