JSON Handling in Scala
In this lesson, you will learn how to work with JSON (JavaScript Object Notation) in Scala. JSON is the most commonly used data format for APIs, web services, and microservice communication.
Scala provides powerful libraries to parse, generate, and manipulate JSON in a safe and expressive way.
What Is JSON?
JSON is a lightweight data-interchange format that is easy for humans to read and machines to parse.
It represents data using:
- Objects (key-value pairs)
- Arrays
- Strings, numbers, booleans, and null
Example of JSON Data
Below is a simple JSON object representing a user.
{
"id": 1,
"name": "Scala",
"active": true
}
JSON Libraries in Scala
Scala does not include JSON handling in the standard library. Popular JSON libraries include:
- Play JSON
- Circe
- uPickle
In this lesson, we will use Play JSON because it is simple, powerful, and widely used.
Adding Play JSON Dependency
Add the following dependency to your build.sbt file.
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.10.0"
Importing Play JSON
Once the dependency is added, import Play JSON into your Scala file.
import play.api.libs.json._
Parsing JSON Strings
You can parse a JSON string into a Scala JSON object using Json.parse.
val jsonString =
"""{"id": 1, "name": "Scala", "active": true}"""
val jsonValue = Json.parse(jsonString)
The result is a JsValue, which represents JSON data in Scala.
Accessing JSON Fields
You can extract values from JSON using path operators.
val name = (jsonValue \ "name").as[String]
val active = (jsonValue \ "active").as[Boolean]
This safely extracts values with the expected data type.
Handling Missing Fields
To avoid runtime errors, use asOpt when fields may be missing.
val age = (jsonValue \ "age").asOpt[Int]
This returns an Option[Int], which may be None.
Creating JSON Objects
You can build JSON objects programmatically using Json.obj.
val newJson = Json.obj(
"id" -> 2,
"name" -> "Play JSON",
"active" -> false
)
Working with JSON Arrays
JSON arrays can be created and accessed easily.
val jsonArray = Json.arr(
Json.obj("id" -> 1),
Json.obj("id" -> 2)
)
jsonArray.value.foreach(println)
Converting Case Classes to JSON
Scala case classes work very well with JSON.
case class User(id: Int, name: String, active: Boolean)
implicit val userWrites = Json.writes[User]
val user = User(1, "Scala", true)
val userJson = Json.toJson(user)
Parsing JSON into Case Classes
You can also convert JSON back into Scala objects.
implicit val userReads = Json.reads[User]
val parsedUser = jsonValue.as[User]
JSON Validation
Play JSON provides validation to safely handle invalid data.
jsonValue.validate[User] match {
case JsSuccess(user, _) => println(user)
case JsError(errors) => println(errors)
}
Real-World Use Cases
- Parsing API responses
- Sending JSON in HTTP requests
- Reading configuration files
- Storing structured data
📝 Practice Exercises
Exercise 1
Parse a JSON string and extract a field.
Exercise 2
Convert a Scala case class into JSON.
Exercise 3
Validate JSON data before using it.
✅ Practice Answers
Answer 1
val value = (jsonValue \ "name").as[String]
Answer 2
Json.toJson(User(2, "Scala", false))
Answer 3
jsonValue.validate[User]
What’s Next?
In the next lesson, you will learn about File Handling and how Scala reads and writes data from files.