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

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


Play framework has pretty printing support built-in:

import play.api.libs.json.JsonJson.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)  }}


You can use Gson to pretty print Json string, don't know about scala; but here is a Java example which you can convert to scala and use it:

Gson gson = new GsonBuilder().setPrettyPrinting().create();String jsonStr = gson.toJson(obj);System.out.println(jsonStr);