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

2

16

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?

Seicento answered 24/11, 2013 at 14:31 Comment(2)
Is there any benefit to having beautified JSON? If it's just for debugging, you can use a browser plugin like JSONView for Firefox to format it. Sending beautified JSON just wastes bandwidth.Agueweed
default behavior is the minified JSON. only when supplying the pretty flag as a query param, you'll get the result beautified. benefits? it's readable. and sometimes you'll want to see a human readable representation of your'e data. take a look at elasticsearch for example. they do just that. by supplying a pretty flag, you can see all sort of data on your node/cluster. this is quite usefull.Seicento
A
30

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)
  }
}
Americanism answered 24/11, 2013 at 14:47 Comment(2)
would play take care of everything a json response should have even if i use a String instead of JsObject?Seicento
Probably not, but "everything" really is just the content type. I edited my answer to show what is necessary to enforce other content types, it's no biggie.Americanism
E
-3

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);
Everything answered 24/11, 2013 at 14:42 Comment(1)
this won't help me. since i'm returning an http response, i need to use play's json object, and the play framework would take care of all sort of annoying things i don't want to define my self. like content-type header, etc'... and BTW, i can get the pretty json as string directly. no need for external tools. but again, the string won't do me much good :\Seicento

© 2022 - 2024 — McMap. All rights reserved.