• Stars
    star
    359
  • Rank 118,537 (Top 3 %)
  • Language
    Scala
  • License
    Apache License 2.0
  • Created almost 8 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The Play JSON library

Play JSON

Twitter Follow Discord GitHub Discussions StackOverflow YouTube Twitch Status OpenCollective

Build Status Maven Repository size Scala Steward badge Mergify Status

Play JSON is a powerful Scala JSON library, originally developed by the Play team for use with Play Framework. It uses Jackson for JSON parsing and has no Play dependencies.

We've provided some documentation here on how to use Play JSON in your app (without Play). For more information on how to use Play JSON in Play, please refer to the Play documentation.

Getting Started

To get started, you can add play-json as a dependency in your project:

  • sbt
    libraryDependencies += "org.playframework" %% "play-json" % -version-
  • Gradle
    compile group: 'org.playframework', name: 'play-json_2.13', version: -version-
    
  • Maven
    <dependency>
      <groupId>org.playframework</groupId>
      <artifactId>play-json_2.13</artifactId>
      <version>-version-</version>
    </dependency>

See GitHub releases for the correct version.

Play JSON supports Scala 2.12, 2.13 and Scala 3.3+. Choosing the right JAR is automatically managed in sbt. If you're using Gradle or Maven then you need to use the correct version in the artifactId.

JSON AST

The base type in Play JSON is play.api.libs.json.JsValue, and has several subtypes representing different JSON types:

  • JsObject: a JSON object, represented as a Map. Can be constructed from an ordered Seq or any kind of Map using JsObject.apply
  • JsArray: a JSON array, consisting of a Seq[JsValue]
  • JsNumber: a JSON number, represented as a BigDecimal.
  • JsString: a JSON string.
  • JsBoolean: a JSON boolean, either JsTrue or JsFalse.
  • JsNull: the JSON null value.

The play.api.libs.json package includes several features for constructing JSON from scratch, as well as for converting to and from case classes.

Basic reading and writing

The play.api.libs.json.Json object has several methods for reading and writing:

Json.parse parses a JSON string or InputStream into a JSON tree:

val json: JsValue = Json.parse("""
{
  "name" : "Watership Down",
  "location" : {
    "lat" : 51.235685,
    "long" : -1.309197
  },
  "residents" : [ {
    "name" : "Fiver",
    "age" : 4,
    "role" : null
  }, {
    "name" : "Bigwig",
    "age" : 6,
    "role" : "Owsla"
  } ]
}
""")

and Json.stringify is used to convert a JsValue to a String of JSON:

val jsonString = Json.stringify(json)
// {"name":"Watership Down","location":{"lat":51.235685,"long":-1.309197},"residents":[{"name":"Fiver","age":4,"role":null},{"name":"Bigwig","age":6,"role":"Owsla"}]}

Traversing a JsValue

Play JSON provides a traversal DSL that lets you query fields in the JSON:

Simple path \

Applying the \ operator will return the property corresponding to the field argument, supposing this is a JsObject.

val lat = (json \ "location" \ "lat").get
// returns JsNumber(51.235685)

The (json \ "location" \ "lat") returns a JsLookupResult which may or may not contain a value. Note that the get operation is not always safe; it throws an exception if the path doesn't exist.

You can also use \ to look up indices within a JsArray:

val bigwig = (json \ "residents" \ 1).get
// returns {"name":"Bigwig","age":6,"role":"Owsla"}

Recursive path \\

Applying the \\ operator will do a lookup for the field in the current object and all descendants.

val names = json \\ "name"
// returns Seq(JsString("Watership Down"), JsString("Fiver"), JsString("Bigwig"))

Index lookup

You can retrieve a value in a JsObject or JsArray using an apply operator with the index number or key.

val name = json("name")
// returns JsString("Watership Down")

val bigwig = json("residents")(1)
// returns {"name":"Bigwig","age":6,"role":"Owsla"}

Like get, this will throw an exception if the index doesn't exist. Use the Simple Path \ operator and validate or asOpt (described below) if you expect that they key may not be present.

Reading and writing objects

To convert a Scala object to and from JSON, we use Json.toJson[T: Writes] and Json.fromJson[T: Reads] respectively. Play JSON provides the Reads and Writes typeclasses to define how to read or write specific types. You can get these either by using Play's automatic JSON macros, or by manually defining them.

You can also read JSON from a JsValue using validate, as and asOpt methods. Generally it's preferable to use validate since it returns a JsResult which may contain an error if the JSON is malformed.

For example:

val unsafeName = (json \ "name").as[String]
// "Watership Down"

val unsafeBogusName = (json \ "bogus").as[String]
// throws exception

val nameOption = (json \ "name").asOpt[String]
// Some("Watership Down")

val bogusOption = (json \ "bogus").asOpt[String]
// None

val nameResult = (json \ "name").validate[String]
// JsSuccess("Watership Down")

val bogusResult = (json \ "bogus").validate[String]
// JsError

val unsafeName2 = json("name").as[String]
// "Watership Down"

val unsafeBogusName2 = json("bogus").as[String]
// throws exception

Automatic conversion

Usually you don't need to traverse JSON AST directly. Play JSON comes equipped with some convenient macros to convert to and from case classes.

For example, suppose I have the following class:

case class Resident(name: String, age: Int, role: Option[String])

I can define a Reads (JSON parser), Writes (JSON writer) using convenient macros:

implicit val residentReads = Json.reads[Resident]
implicit val residentWrites = Json.writes[Resident]

I can also define a Format that does both:

implicit val residentFormat = Json.format[Resident]

With the Reads and/or Writes in scope, I can then easily convert my class using toJson and fromJson

Constructing Reads and Writes

Play JSON provides a convenient functional DSL for constructing Reads and Writes. For example, assume I have the following classes:

case class Location(lat: Double, long: Double)
case class Resident(name: String, age: Int, role: Option[String])
case class Place(name: String, location: Location, residents: Seq[Resident])

Then I could construct Reads for them as follows:

import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._

implicit val locationReads: Reads[Location] = (
  (JsPath \ "lat").read[Double](min(-90.0) keepAnd max(90.0)) and
  (JsPath \ "long").read[Double](min(-180.0) keepAnd max(180.0))
)(Location.apply _)

implicit val residentReads: Reads[Resident] = (
  (JsPath \ "name").read[String](minLength[String](2)) and
  (JsPath \ "age").read[Int](min(0) keepAnd max(150)) and
  (JsPath \ "role").readNullable[String]
)(Resident.apply _)

implicit val placeReads: Reads[Place] = (
  (JsPath \ "name").read[String](minLength[String](2)) and
  (JsPath \ "location").read[Location] and
  (JsPath \ "residents").read[Seq[Resident]]
)(Place.apply _)


val json = { ... }

json.validate[Place] match {
  case s: JsSuccess[Place] => {
    val place: Place = s.get
    // do something with place
  }
  case e: JsError => {
    // error handling flow
  }
}

Similarly, I could construct Writes like this:

import play.api.libs.json._
import play.api.libs.functional.syntax._

implicit val locationWrites: Writes[Location] = (
  (JsPath \ "lat").write[Double] and
  (JsPath \ "long").write[Double]
)(unlift(Location.unapply))

implicit val residentWrites: Writes[Resident] = (
  (JsPath \ "name").write[String] and
  (JsPath \ "age").write[Int] and
  (JsPath \ "role").writeNullable[String]
)(unlift(Resident.unapply))

implicit val placeWrites: Writes[Place] = (
  (JsPath \ "name").write[String] and
  (JsPath \ "location").write[Location] and
  (JsPath \ "residents").write[Seq[Resident]]
)(unlift(Place.unapply))


val place = Place(
  "Watership Down",
  Location(51.235685, -1.309197),
  Seq(
    Resident("Fiver", 4, None),
    Resident("Bigwig", 6, Some("Owsla"))
  )
)

val json = Json.toJson(place)

It is also possible to implement custom logic by implementing the Reads, Writes and/or Format traits manually, but we recommend using the automatic conversion macros or the functional DSL if possible.

Manual JSON construction

JSON can also be manually constructed using a DSL:

val json: JsValue = Json.obj(
  "name" -> "Watership Down",
  "location" -> Json.obj("lat" -> 51.235685, "long" -> -1.309197),
  "residents" -> Json.arr(
    Json.obj(
      "name" -> "Fiver",
      "age" -> 4,
      "role" -> JsNull
    ),
    Json.obj(
      "name" -> "Bigwig",
      "age" -> 6,
      "role" -> "Owsla"
    )
  )
)

Releasing a new version

See https://github.com/playframework/.github/blob/main/RELEASING.md

License

Play JSON is licensed under the Apache license, version 2. See the LICENSE file for more information.

More Repositories

1

playframework

The Community Maintained High Velocity Web Framework For Java and Scala.
Scala
12,527
star
2

play1

Play framework
Java
1,580
star
3

play-slick

Slick Plugin for Play
Scala
803
star
4

twirl

Twirl is Play's default template engine
Scala
542
star
5

play-samples

Play Framework Sample Projects
JavaScript
525
star
6

play-plugins

CachePlugin
JavaScript
444
star
7

play-mailer

Play mailer plugin
Scala
250
star
8

anorm

The Anorm database library
Scala
237
star
9

play-scala-starter-example

Play Scala Starter Template (ideal for new users!)
CSS
236
star
10

play-ws

Standalone Play WS, an async HTTP client with fluent API
Scala
222
star
11

play-scala-rest-api-example

Example Play Scala application showing REST API
Scala
213
star
12

play-scala-react-seed

❄️ Scala Play + React seed project with full-fledged build process
Shell
203
star
13

play-scala-websocket-example

Example Play Scala application showing WebSocket use with Akka actors
Scala
195
star
14

play-java-starter-example

Play starter project in Java (ideal for new users!)
CSS
161
star
15

play-scala-isolated-slick-example

Example Play Slick Project
Scala
154
star
16

netty-reactive-streams

Reactive streams implementation for Netty.
Java
113
star
17

scalatestplus-play

ScalaTest + Play
Scala
110
star
18

play-ebean

Play Ebean module
Java
103
star
19

play-socket.io

Play socket.io support
Scala
93
star
20

play-java-websocket-example

Example Play Java application showing Websocket usage with Akka actors
Java
88
star
21

play-scala-angular-seed

πŸ€ Scala Play 2.7.x + Angular 8 with Angular CLI seed project with full-fledged build process
TypeScript
84
star
22

prune

Performance testing tool for Play Framework
Scala
81
star
23

play-silhouette

Silhouette is an authentication library for Play Framework applications that supports several authentication methods, including OAuth1, OAuth2, OpenID, CAS, 2FA, TOTP, Credentials, Basic Authentication or custom authentication schemes.
Scala
78
star
24

play-scala-seed.g8

Play Scala Seed Template: run "sbt new playframework/play-scala-seed.g8"
Scala
74
star
25

play-scala-slick-example

Example Play Scala project with Slick
Scala
59
star
26

modules.playframework.org

Java
57
star
27

play-scala-secure-session-example

An example Play application showing encrypted session management
Scala
56
star
28

play-java-ebean-example

Example Play application showing Java with Ebean
Java
53
star
29

play-java-angular-seed

🍁 Java Play 2.7.x + Angular 8 with Angular CLI seed project with full-fledged build process
TypeScript
53
star
30

play-scala-macwire-di-example

Sample project for compile-time DI with Macwire
Scala
47
star
31

play-java-rest-api-example

REST API using Play in Java
Java
45
star
32

play-scala-chatroom-example

Play chatroom with Scala API
Scala
44
star
33

play-scala-tls-example

A Play application using HTTPS and WS with optional client authentication
Scala
44
star
34

play-java-react-seed

πŸŒ€ Java Play 2.7.x + React seed project with full-fledged build process
Shell
44
star
35

playframework.com

The Play Framework website
Scala
43
star
36

play-scala-streaming-example

Example Play application showing Comet and Server Sent Events in Scala
Scala
43
star
37

play-scala-anorm-example

Example Play Database Application using Anorm
Scala
41
star
38

play-java-dagger2-example

Play Application using Dagger 2 for Compile Time DI
Java
40
star
39

play-scala-compile-di-example

Example Play Project using compile time dependency injection and Play WS with ScalaTest
Scala
38
star
40

play-soap

Play SOAP support
Scala
35
star
41

play-grpc

Play + Pekko gRPC
Scala
35
star
42

play-java-jpa-example

Example Play Java project with JPA database integration
Java
35
star
43

play-java-chatroom-example

Example Chatroom with Java API
Java
34
star
44

play-scala-fileupload-example

An example Play application showing custom multiform fileupload in Scala
Scala
29
star
45

play-java-seed.g8

Play Java Seed template: use "sbt new playframework/play-java-seed.g8"
Java
23
star
46

play-doc

Play documentation rendering support
Scala
21
star
47

play-webgoat

A vulnerable Play application for attackers.
Scala
18
star
48

play-iteratees

Scala
18
star
49

play-scala-forms-example

Example Play Project showing form processing
Scala
16
star
50

play-glassfish

Play container for Glassfish
Java
16
star
51

cachecontrol

Minimal HTTP cache management library in Scala
Scala
14
star
52

play-file-watch

This is the Play File Watch library
Java
14
star
53

play-enhancer

Java
14
star
54

play-scala-log4j2-example

An example Play project using Log4J 2 as the logging engine
Scala
14
star
55

play-java-fileupload-example

An example Play application showing custom multiform fileupload in Java
Java
14
star
56

interplay

Common sbt plugins for Play modules
Scala
12
star
57

play-generated-docs

Generated docs for publishing to the Play website.
11
star
58

play-scala-hello-world-tutorial

Hello World Tutorial for Play in Scala
HTML
10
star
59

play-spring-loader

An application loader for Play that uses Spring as the dependency injection framework
Scala
10
star
60

play-java-streaming-example

Example Play application showing Comet and Server Sent Events in Java
JavaScript
9
star
61

play-scala-grpc-example

Example for akka-grpc services embedded in Play framework applications (Scala)
CSS
9
star
62

play-meta

Team management & cross-repository effort tracking
Shell
8
star
63

play-java-hello-world-tutorial

Play Hello World tutorial in Java
HTML
6
star
64

omnidoc

Play aggregated documentation
Scala
6
star
65

.github

Scala
5
star
66

play-java-forms-example

Play Project Template showing Java Forms Processing
Java
5
star
67

play-java-compile-di-example

Example Play application using compile time DI with Java API
Java
4
star
68

play-java-grpc-example

Example for akka-grpc services embedded in Play framework applications (Java)
CSS
4
star
69

templatecontrol

Template Control for Play templates and other examples
Scala
4
star
70

play-quota-scala-example

An example of User Quotas using Play and Scala
Scala
3
star
71

modules.playframework.com

The Play Framework module index
Scala
3
star
72

play-native-loader

Loading native libraries in Play Framework
Java
3
star
73

play-quota-java-example

An example application using Play Quota with Java API
Java
3
star
74

playframework.github.io

2
star
75

jnotify

Scala
2
star
76

play-courses

Courses on play using the course management tools
CSS
1
star
77

play-antora-ui

CSS
1
star