The Scala Toolkit

How to modify JSON?

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"

ujson.read returns a mutable representation of JSON that you can update. Fields and elemnts can be added, modified, or removed.

First you read the JSON string, then you update it in memory, and finally you write it back out again.

// Parse the JSON string
val json: ujson.Value = ujson.read("""{"name":"John","pets":["Toolkitty","Scaniel"]}""")

// Update it
json("name") = "Peter"
json("nickname") = "Pete"
json("pets").arr.remove(1)

// Write it back to a String
val result: String = ujson.write(json)
println(result)
// prints: {"name":"Peter","pets":["Toolkitty"],"nickname":"Pete"}

Contributors to this page: