Search code examples
scalaplay-json

How to replace value in json using scala play json


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.


Solution

  • 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.