How to replace a JSON value in Play

json, playframework-2.0, playframework-2.1, scala

Solution

According to the Play Documentation, JsObjects have a method `++` that will merge two JsObjects. So, when you have your new integer value, you simply need:

val updatedJson = json.as[JsObject] ++ Json.obj("customerId" -> newValue)

As of Play 2.4.x you can use `+`:

val updatedJson = json.as[JsObject] + ("customerId" -> newValue)

(NOTE: the `+` method was added already in 2.1.x but adds a duplicate field to the object instead of replacing the existing value in versions prior to 2.4.x)

Problem

How do I replace a value in a JSON value in Play? Code to illustrate: ``` def newReport() = Action(parse.json) { request => var json = request.body if((json \ "customerId").as[Int] == -1){ // replace customerId after some logic to find the new value } json.validate[Report](Reports.readsWithoutUser).map { case _: Report => ```

Original source