简体   繁体   中英

How filter a JSLookup/JSObject with the Scala Play library

Say I have some params coming from our API clients like this:

val params = (request \ "params")

I want to filter them and remove certain key/values. Like if I get:

{
  "foo": "bar",
  "hello": "world"
}

I want to filter it to

{
  "foo": "bar"
}

Here's my WIP code but, as more advanced Scala people will probably tell right away, it doesn't work.

val params = (request \ "params").get.as[List[JsObject]]

val blacklistedParams = Seq("foo")

val approvedParams = params.filter((param: JsObject) => {
  !blacklistedParams.contains(param)
})

That first line always fails. I've tried doing .get.as in all sorts of types but always get errors. I'm still new to Scala and types in general.

I think I figured out a way:

val params = (request \ "params").get.as[Map[String, JsValue]]

val blacklistedParams = Seq("foo")

val approvedParams = params.filter((param) => {
  !blacklistedParams.contains(param._1)
})

My only annoyance with this method is that ._1 . To me its not very clear for the next person that this is the key of the key/val pair of the params.

You can use -

val filtered = (request \ "params").as[JsObject] - "hello" 

Full example:

def index = Action{
  val json = Json.obj(
      "params" -> Json.obj(
          "foo" -> "bar",
          "hello" -> "world"))

  val filtered = (json \ "params").as[JsObject] - "hello"         

  Ok(filtered)
}

output:

{
  foo: "bar"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM