0

I knew we can update the JsObject by key, however, how can I update the key of key in JsObject.

For example,

val queryText = (Json.parse(normalQuery) \"query" \"query_string" \"query").as[String]

I can get the string value, however, how can I update it?

  updatedJson ++ Json.obj("query/query_string/query" -> Json.toJson("new_test"))

This did not work.

user48135
  • 481
  • 5
  • 13

1 Answers1

0

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
Cyrille Corpet
  • 5,265
  • 1
  • 14
  • 31