How can one send, using the Play! framework, a JSON response that is formatted to be human-readable?
For example, I'm looking for something like:
def handleGET(path:String) = Action{ implicit request =>
val json = doSomethingThatReturnsAJson(path,request)
request.getQueryString("pretty") match {
case Some(_) => //some magic that will beautify the response
case None => Ok(json)
}
}
My search led me to JSON pretty-print, which was not very helpful on it's own, but it did say the ability should be integrated in future versions. That was play 2.1.X, so, I guess it already exists somewhere in the 2.2X version of play?
The Play JSON library. The play. api. libs. json package contains data structures for representing JSON data and utilities for converting between these data structures and other data representations.
JsValue can be a string, numeric, object or array. Therefore you can't assume that it has key value pairs. If you have a val x: JsValue that you know is a JsObject you can use x.as[JsObject] to cast it or if you're not sure it's a JsObject you can use x.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Play framework has pretty printing support built-in:
import play.api.libs.json.Json
Json.prettyPrint(aJsValue)
So in your case, it would be sufficient to do the following:
def handleGET(path:String) = Action { implicit request =>
val json = doSomethingThatReturnsAJson(path, request)
request.getQueryString("pretty") match {
case Some(_) => Ok(Json.prettyPrint(json)).as(ContentTypes.JSON)
case None => Ok(json)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With