检查play.api.libs.json.Json中是否存在密钥

Gov*_*ngh 14 collections json scala playframework scala-collections

contains 喜欢的功能 play.api.libs.json.Json

val data=Map("id" -> "240190", "password" -> "password","email" -> "email@domain.com")

data.contains("email")//true


val info=Json.obj("id" -> "240190", "password" -> "password","email" -> "email@domain.com")
Run Code Online (Sandbox Code Playgroud)

现在如何检查是否info包含email

End*_*Neu 21

info.keys.contains("email")
Run Code Online (Sandbox Code Playgroud)

.keys给你回Set与键值,然后你可以调用contains方法,我不知道还有一个更直接的方式来做到这一点.


Mah*_*ari 7

(info \ "email").asOpt[String].isEmpty
Run Code Online (Sandbox Code Playgroud)

因为asOpt会返回Optional,我们可以进行isEmpty简单检查,这样可以做我们想要的.

  • 一些解释可能有助于未来的访客 (3认同)
  • 您可以编辑答案以添加说明,而不是将其写为注释. (2认同)

San*_*eta 5

(info \ "email").asOpt[String] match {
  case Some(data) => println("here is the value for the key email represented by variable data" + data)
  case None => println("email key is not found") 
}
Run Code Online (Sandbox Code Playgroud)