Working with JSON data on the Play Framework for Scala: Examples
Source

Working with JSON data on the Play Framework for Scala: Examples

Last updated:

WIP Alert This is a work in progress. Current information is correct but more content will probably be added in the future.

HEADS-UP There's another post on how to define complex validators for JSON data

Building JsObject piece by piece

import play.api.libs.json._

val person = Json.obj(
    "name" -> "John Doe",
    "age" -> 26)

// {name: "John Doe", age: 26}

A JsValue can be any json value, such as a JsObject, JsArray and so on

Parsing a JSON String into a JSValue

import play.api.libs.json._

val myString = """{ "foo":"bar" }"""

val json: JsValue = Json.parse(myString)
// json is a JsValue

Converting a JSObject back into a String

import play.api.libs.json._

val person = Json.obj(
    "name" -> "John Doe",
    "age" -> 26)

val myString:String = Json.stringify(person)

Converting from JsValue to a model

Acessing JSObject properties

And also JSArray elements by index

TODO talk about "\" and "\\" and (num) for arrays

Sending an appropriate JSON response from an action

TODO create result and set content type = application/json (or is it text/json?).

References

Dialogue & Discussion