Remove a key from a JsValue in Scala

This can be done as a JsObject, which extends JsValue:

body.as[JsObject] - "id"

I came across this question when I wanted to remove a nested field from a json object, and since subtracting doesn't work for nested fields, I'm adding the solution I ended up using.

To remove a field from a JsObject you can use prune to remove the entire path to that field.

For the example above -

val p = JsPath \ "id"
val res = p.prune(body.as[JsObject]).get

If you had a nested object like this -

{
     "url": "www.google.com",
     "id":  {"first": "123", "second": "456"}
     "count" : 1,
     "label" : "test"  
 }

you could create a more specific path -

val p = JsPath \ "id" \ "second"
val res = p.prune(body.as[JsObject]).get

You can use as Method as[JsObject] with minus - symbol. Like Below.

body.as[JsObject] - "id"

Below has detailed explanation step by step. Let's see with custom object.

val json: JsValue = JsObject(Seq(
      "error" -> JsBoolean(false),
      "result" -> JsNumber(calcResult),
      "message" -> JsString(null)
    ))

It can be picked by as Method and removed "-" symbol.

/* Removing Message Property and keep the value in successResult Variable */
val successResult = json.as[JsObject] - "message"

Take a look at Body Parser in Scala to know about Choosing an explicit body parser, Combining body parsers and Writing a custom body parser.