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 =>
First you would need to convert it to a JavaScript Object. Once it is an Object, then you can just use dot notation into the object to change the values that you want. Lastly, you would convert that JavaScript Object back into a JSON string.
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.
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.
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)
One approach is, as Marc B says, convert the JSON to something like a case class, manipulate that, and then create a new JSON.
However you can also use JSON 'transformers'. Effectively what you do is build a Reads[SomeThing] object. This object is passed to the transform method which you call on your JSON object. It will change the JSON object and return a Success(result) or Failure(error) where result is the new modified JSON. Here's a (comparatively)very simple example:
using json of format: {key -> value}
def jsonXForm(value: String) = (__ \ "customerId").json.update(
(__ \ "customerId").json.put(JsString(value))
)
json.transform(jsonXForm(yourNewValue)) match {...}`
There is a decent guide here
Something along the lines of:
val updatedJson = if((request.body \ "customerId").as[Int] == -1){
val newId = JsObject(Seq(("customerId",JsString("ID12345"))))
(request.body ++ newId).as[JsValue]
} else request.body
updatedJson.validate[Report](Reports.readsWithoutUser).map {
case _: Report =>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With