Remove a key from a JsValue in Scala

前端 未结 3 1068
星月不相逢
星月不相逢 2021-02-13 17:34

It\'s probably a very easy question but I\'m having trouble finding a clean/working solution. I just want to remove a field from a json object I have. Let\'s say I have :

3条回答
  •  无人共我
    2021-02-13 18:07

    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
    

提交回复
热议问题