简体   繁体   English

如何使用Scala Play库过滤JSLookup / JSObject

[英]How filter a JSLookup/JSObject with the Scala Play library

Say I have some params coming from our API clients like this: 假设我有一些来自我们的API客户端的参数,如下所示:

val params = (request \ "params")

I want to filter them and remove certain key/values. 我想filter它们并删除某些键/值。 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. 这是我的WIP代码,但是,随着更高级的Scala人员可能会立即告诉您,它不起作用。

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. 我尝试过.get.as ,但总是会出错。 I'm still new to Scala and types in general. 我还是Scala和类型的新手。

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 . 我对这种方法的唯一烦恼是._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"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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