Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to respond with a pretty-printed JSON object using play framework?

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?

like image 553
gilad hoch Avatar asked Nov 24 '13 14:11

gilad hoch


People also ask

What is play JSON?

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.

What is a JsValue?

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.

Which of the following methods convert a JavaScript object to and from a JSON string?

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.


1 Answers

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)
  }
}
like image 109
Leo Avatar answered Oct 13 '22 18:10

Leo