Check if an object has a field in json4s/lift-json

douglaz picture douglaz · Feb 9, 2014 · Viewed 9.2k times · Source

I have a json with some fields and I want to check if some of them are present. I'm extracting the value and testing it against JNothing, but it is too verbose:

val json: JValue = ...

val jsonIsType1 = (json \ "field1") != JNothing && (json \ "field2") != JNothing

Is there a more compact way to check the presence of a field in a json object using json4s/lift-json? Ideally something like:

val jsonIsType1 = json.has("field1") && json.has("field2")

Answer

Damiya picture Damiya · Feb 10, 2014

JValue doesn't have a 'has' operator, but the power of Scala's implicits allows you to add that functionality without too much trouble.

Here's an example of that:

implicit class JValueExtended(value: JValue) {
  def has(childString: String): Boolean = {
    if ((value \ childString) != JNothing) {
      true
    } else {
      false
    }
  }
}

Usage example:

scala> val json = Json.parse("""{"field1": "ok", "field2": "not ok"}""")

scala> json.has("field1")
res10: Boolean = true