Remove a key from a JsValue in Scala

前端 未结 3 1065
星月不相逢
星月不相逢 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:04

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

    body.as[JsObject] - "id"
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-13 18:22

    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.

    0 讨论(0)
提交回复
热议问题