Check if a key exists in play.api.libs.json.Json
Asked Answered
E

4

16

contains like functionality for play.api.libs.json.Json

val data=Map("id" -> "240190", "password" -> "password","email" -> "[email protected]")

data.contains("email")//true


val info=Json.obj("id" -> "240190", "password" -> "password","email" -> "[email protected]")

now how to check info contains email or not?

Emeldaemelen answered 23/7, 2014 at 7:35 Comment(0)
J
24
info.keys.contains("email")

The .keys gives you back a Set with the key values and then you can call the contains method, I'm not sure there's a more direct way to do it.

Jonell answered 23/7, 2014 at 7:49 Comment(2)
keys yields a Set.Palliative
Thanks, It was a typo.Jonell
L
8
(info \ "email").asOpt[String].isEmpty

as asOpt would return Optional, we can have isEmpty simple check, this would do what we want.

Loree answered 22/7, 2017 at 12:18 Comment(3)
Some explanation might help future visitors.Demos
@errhunter thankq! as asOpt would return Optional, we can have isEmpty simple check, this would do what we want.Loree
You can edit your answer to add the explanation, instead of writing it as a comment.Kaleb
M
6
(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") 
}
Melchizedek answered 1/9, 2016 at 6:12 Comment(1)
This won't work when you do things like .asOpt[Boolean], which will always give you a Some(false) when the key doesn't exist.Angelitaangell
S
0

(info \ "email").asOpt[String] works only if email is a string. If email is an object, (info \ "email").asOpt[String] will be None. An alternative is to match (info \ "email").toOption to Some or None.

Stapleton answered 10/1 at 0:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.