Solution 1
You should read the documentation on JsPath. The method you're looking for is JsPath.json.update
:
import play.api.libs.json._
val baseJson = Json.obj("query" -> Json.obj("query_string" -> Json.obj("query" -> "old_value")))
val updater: Reads[JsObject] = __.json.update((__ \"query" \"query_string" \"query").json.put(JsString("new_value")))
val updated: JsResult[JsObject] = baseJson.transform(updater)
Solution 2
You can also add a field using ++
as you tried to do, but you need to define your object properly:
val overrider = Json.obj("query" -> Json.obj("query_string" -> Json.obj("query" -> "new_value")))
val badOverriden = baseJson ++ overrider
Actually, this does not work, because ++
is not recursive: it only overrides field at the top level of the JSON object. However, you can use deepMerge
that does the same, recursively:
val overriden = baseJson deepMerge overrider