jsonscalalift-jsonjson4s

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


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")

Solution

  • 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 = {
        (value \ childString) != JNothing
      }
    }
    

    Usage example:

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