ps0604 ps0604 - 4 months ago 16
Scala Question

Play: how to append a list to an existing JSON variable?

Given the following json variable

var json: JsValue = JsObject(Seq(
"retcode" -> JsString("1")

and the following Writes object for a

implicit val w2 : Writes[User] = (
(JsPath \ "id").write[Int] and
(JsPath \ "userid").write[String] and
(JsPath \ "name").write[String]
) (unlift(User.unapply))

Assuming I have a list of users

var list : List[User] = ( some list )

How to append the list to the initial


Assuming you want to end up with something like this (the users list added as another key/value to your original object):

  "retcode" : "1",
  "users" : [ {
    "id" : "1",
    "userid" : "u1",
    "name" : "Bob"
  }, {
    "id" : "2",
    "userid" : "u2",
    "name" : "Fred"
  } ]

you can do:

val newJson =[JsObject] + ("users" -> Json.toJson(list))

You can skip the .as[JsObject] if you declare json as a JsObject to start with, rather than a JsValue. (The as is potentially unsafe if you don't know your JSON definitely represents an object, as opposed to a list or a primitive. See using validation for a better way to handle that.)