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]:
In [2]:
import org.yaml.snakeyaml.Yaml
Out[2]:
In [3]:
import scala.collection.JavaConverters._
Out[3]:
In [4]:
val yaml = new Yaml()
Out[4]:
In [5]:
val document = "\n- Hesperiidae\n- Papilionidae\n- Apatelodidae\n- Epiplemidae"
Out[5]:
In [6]:
val obj = yaml.load(document).asInstanceOf[java.lang.Object]
Out[6]:
In [7]:
obj.isInstanceOf[java.util.List[String]]
Out[7]:
In [12]:
obj.isInstanceOf[Seq[String]]
Out[12]:
In [9]:
obj.asInstanceOf[java.util.List[String]]
Out[9]:
In [15]:
obj.asInstanceOf[java.util.List[String]]
Out[15]:
In [13]:
obj.asInstanceOf[Seq[String]]
In [30]:
val list = yaml.load(document).asInstanceOf[java.util.List[String]]
Out[30]:
In [12]:
list
Out[12]:
In [15]:
val doc = """
|aa:
| - x
| - y
|bb: z
""".stripMargin
Out[15]:
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]:
In [23]:
yaml.load(inputStream).asInstanceOf[java.util.Map[String, Any]]
Cast to Map¶
In [36]:
104.62 / 8
Out[36]:
In [ ]: