0

I'm at scala play 2.6.10 I have a json:

{"_id": {"$oid": "VALUE"}, "anotherField": "anotherValue"}

The goal is to get rid of {"$oid": "VALUE"} and put "VALUE" as the value for "_id" field.

Expected result:

{"_id": "VALUE", "anotherField": "anotherValue"}

Tried this one: https://www.playframework.com/documentation/2.8.x/ScalaJsonTransformers

i have absolutely no idea how to combine

  • extract specific branch value
  • "prune" of JsObject
  • "update" deleted JsObject with JsString.

BTW, is there any simpler API for doing it? This one is way too complex.

Capacytron
  • 3,425
  • 6
  • 47
  • 80
  • I've seen similar examples. Can't make it work since I "update" JsObject to JsString. Don't understand how to express it with that Json DSL – Capacytron Mar 09 '21 at 13:35
  • Look like MongoDB extended syntax, so rather use a dedicated lib – cchantep Mar 09 '21 at 22:41
  • what is dedicated lib? can mongo-scala-driver interact with scala case classes directly? – Capacytron Mar 10 '21 at 14:41
  • 1
    http://reactivemongo.org/releases/1.0/documentation/json/overview.html#documents-and-values – cchantep Mar 10 '21 at 14:56
  • Does this answer your question? [How to update a nested json using scala play framework?](https://stackoverflow.com/questions/64280699/how-to-update-a-nested-json-using-scala-play-framework) – Oleg Pyzhcov Mar 12 '21 at 08:03

1 Answers1

2

You can read more about the update documentation at How to update a nested json using scala play framework? In your example you can do something like this:

val jsonString = """{"_id": {"$oid": "VALUE"}, "anotherField": "anotherValue"}
                   |""".stripMargin

val jsonTransformer = (__ \ "_id").json.update(__.read[JsObject].map { _ => JsString("Value") })
Json.parse(jsonString).transform(jsonTransformer) match {
  case JsSuccess(value, _) =>
    println(value)
  case JsError(errors) =>
    println(errors)
}

It outputs:

{"anotherField":"anotherValue","_id":"Value"}

Code run at Scastie.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35