yaml4s
Setup
This library is currently available for Scala binary versions 2.12, 2.13 and 3.2 on JVM, JS and Native.
To use the latest version, include the following in your build.sbt
:
libraryDependencies ++= Seq(
// Cross platform yaml parsing and printing
"dev.hnaderi" %%% "yaml4s-backend" % "0.3.0",
// JSON library integrations
"dev.hnaderi" %%% "yaml4s-circe" % "0.3.0",
"dev.hnaderi" %%% "yaml4s-json4s" % "0.3.0",
"dev.hnaderi" %%% "yaml4s-play-json" % "0.3.0",
"dev.hnaderi" %%% "yaml4s-zio-json" % "0.3.0",
"dev.hnaderi" %%% "yaml4s-spray-json" % "0.3.0",
// Or specific backends
// libyaml is a native only backend using official libyaml C library
"dev.hnaderi" %%% "yaml4s-libyaml" % "0.3.0",
// snake yaml is a jvm only backend
"dev.hnaderi" %%% "yaml4s-snake" % "0.3.0",
// js yaml is a js only backend using `js-yaml` library
"dev.hnaderi" %%% "yaml4s-jsyaml" % "0.3.0",
)
Usage
When using yaml4s-backend
, you can simply use the following:
import dev.hnaderi.yaml4s._
Backend.parse[YAML]("""
data:
- 1
- 2
- 3
""")
// res0: Either[Throwable, YAML] = Right(
// YObj(
// Map(
// "data" -> YArr(Vector(YNumber(YLong(1L)), YNumber(YLong(2L)), YNumber(YLong(3L))))
// )
// )
// )
// Or print to string
Backend.print(
YAML.obj("data" -> YAML.arr(
YAML.number(1),
YAML.number(2),
YAML.number(3)
)
)
)
// res1: String = """data: [1, 2, 3]
// """
You can also use json data structures from your favorite json library:
Circe
import dev.hnaderi.yaml4s.circe._
import io.circe.Json
Backend.parse[Json]("""
data:
- 1
- 2
- 3
""")
// res2: Either[Throwable, Json] = Right(
// JObject(
// object[data -> [
// 1,
// 2,
// 3
// ]]
// )
// )
// Or print to string
Backend.print(
Json.obj("data" -> Json.arr(
Json.fromInt(1),
Json.fromInt(2),
Json.fromInt(3)
)
)
)
// res3: String = """data: [1, 2, 3]
// """
Zio Json
import dev.hnaderi.yaml4s.ziojson._
import zio.json.ast.Json
Backend.parse[Json]("""
data:
- 1
- 2
- 3
""")
// res4: Either[Throwable, Json] = Right(
// Obj(Chunk.Singleton(("data", Arr(Chunk.VectorChunk(Num(1), Num(2), Num(3))))))
// )
Play json
import dev.hnaderi.yaml4s.playjson._
import play.api.libs.json.JsValue
Backend.parse[JsValue]("""
data:
- 1
- 2
- 3
""")
// res5: Either[Throwable, JsValue] = Right(
// JsObject(
// Map("data" -> JsArray(Vector(JsNumber(1), JsNumber(2), JsNumber(3))))
// )
// )
Spray json
import dev.hnaderi.yaml4s.sprayjson._
import spray.json.JsValue
Backend.parse[JsValue]("""
data:
- 1
- 2
- 3
""")
// res6: Either[Throwable, JsValue] = Right(
// JsObject(
// Map("data" -> JsArray(Vector(JsNumber(1), JsNumber(2), JsNumber(3))))
// )
// )
json4s json
import dev.hnaderi.yaml4s.json4s._
import org.json4s.JValue
Backend.parse[JValue]("""
data:
- 1
- 2
- 3
""")
// res7: Either[Throwable, JValue] = Right(
// JObject(List(("data", JArray(List(JInt(1), JInt(2), JInt(3))))))
// )