The Scala Toolkit

How to read and write JSON files?

Language

Using Scala CLI, you can require the entire toolkit in a single line:

//> using toolkit latest

Alternatively, you can require just a specific version of UPickle:

//> using dep com.lihaoyi::upickle:3.1.0

In your build.sbt file, you can add the dependency on the Toolkit:

lazy val example = project.in(file("."))
  .settings(
    scalaVersion := "3.3.4",
    libraryDependencies += "org.scala-lang" %% "toolkit" % "0.1.7"
  )

Alternatively, you can require just a specific version of UPickle:

libraryDependencies += "com.lihaoyi" %% "upickle" % "3.1.0"

In your build.sc file, you can add the dependency to the upickle library:

object example extends ScalaModule {
  def scalaVersion = "3.3.4"
  def ivyDeps =
    Agg(
      ivy"org.scala-lang::toolkit:0.1.7"
    )
}

Alternatively, you can require just a specific version of UPickle:

ivy"com.lihaoyi::upickle:3.1.0"

Read and write raw JSON

To read and write JSON files, you can use uJson and OS-Lib as follows:

// read a JSON file
val json = ujson.read(os.read(os.pwd / "raw.json"))

// modify the JSON content
json("updated") = "now"

//write to a new file
os.write(os.pwd / "raw-updated.json", ujson.write(json))

Read and write Scala objects using JSON

To read and write Scala objects to and from JSON files, you can use uPickle and OS-Lib as follows:

import upickle.default._

case class PetOwner(name: String, pets: List[String])
implicit val ownerRw: ReadWriter[PetOwner] = macroRW

// read a PetOwner from a JSON file
val petOwner: PetOwner = read[PetOwner](os.read(os.pwd / "pet-owner.json"))

// create a new PetOwner
val petOwnerUpdated = petOwner.copy(pets = "Toolkitty" :: petOwner.pets)

// write to a new file
os.write(os.pwd / "pet-owner-updated.json", write(petOwnerUpdated))
import upickle.default.*

case class PetOwner(name: String, pets: List[String]) derives ReadWriter

// read a PetOwner from a JSON file
val petOwner: PetOwner = read[PetOwner](os.read(os.pwd / "pet-owner.json"))

// create a new PetOwner
val petOwnerUpdated = petOwner.copy(pets = "Toolkitty" :: petOwner.pets)

// write to a new file
os.write(os.pwd / "pet-owner-updated.json", write(petOwnerUpdated))

To serialize and deserialize Scala case classes (or enums) to JSON we need an instance of ReadWriter. To understand how uPickle generates it for you, you can read the How to deserialize JSON to an object? or the How to serialize an object to JSON? tutorials.

Contributors to this page: