JSON transformer to delete a key

Hello,
I am writing some code that needs to delete a JSON key that hold a value.
Turns out I cannot use prune , since it’s JsValue I get a validator error that it’s excpecting a JsObject.
It would be handy to have prune to work also on JsValues, as the solution I came up with it works but it’s a little verbose

((__ \ "events")(0) \ "data" ).json.update(
      __.read[JsObject].map{ o => o - "field_to_delete" } 
    )

However the above solution does not work because the path contains an array, looks like I also ran into this old bug https://github.com/playframework/play-json/issues/82

the JSON is like

{ 
  "data" : [
     { 
       "field_to_delete": "aaa",
       "other_field" : "bbb"
    },
...   

I use another transformer to walk the Array and apply the prune.

import play.api.libs.json._
import play.api.libs.json.Reads._
import scala.language.postfixOps

val j = Json.parse("""{
          |  "data" : [
          |     {
          |       "field_to_delete": "aaa",
          |       "other_field" : "bbb"
          |    }
          |    ]
          |    }""".stripMargin)

val t = (__ \ "field_to_delete" ).json.prune

val at = (__  \ "data").json.pick(  of[JsArray].map {case JsArray(xs) => JsArray(xs.map(_.transform(t).get))})

val l = j.transform(at)
Json.prettyPrint(l.get)
1 Like