Search code examples
scalaplay-json

How to check if JsArray holds Objects or Simple types?


I need to write a function that recieve JsValue, and do those steps:

  1. check if its of type Array
  2. if its NOT Array, return the value inside a list
  3. if it IS Array, check if its Array of an object or simple typle (string, boolean etc)
  4. if its Array of simple type return this Array and print "this is an array with simple types"
  5. if its Array of objects return this Array and print "this is an array with objects"

so something like this:

def myFunc(json: JsValue) = {
    if (json.isInstanceOf[JsArray]) {
      // check if list of objects or simple type
      // how do i check if its a list of objects or simple type??
    } else {
      JsArray(json)
    }
}

thanks!


Solution

  • I find pattern matching tends to greatly help in these sorts of situations.

    So we start with a skeleton. Being explicit about the desired result type helps to guide the reasoning.

    def myFunc(json: JsValue): JsArray =
      json match {
        // Fill in cases later
      }
    
    1. if its NOT Array, return the value inside a list
    def myFunc(json: JsValue): JsArray =
      json match {
        case JsArray(members) => ???
        case _ => JsArray(Array(json))
      }
    
    1. if its Array of simple type return this Array and print "this is an array with simple types"
    2. if its Array of objects return this Array and print "this is an array with objects"

    Making some assumptions around the ambiguities (empty array? both simple and objects? nested array?):

    def isSimple(json: JsValue) =
      json match {
        case _: JsArray | _: JsObject => false
        case _ => true
      }
    
    def myFunc(json: JsValue): JsArray =
      json match {
        case arr @ JsArray(members) =>
          // arr is effectively json.asInstanceOf[JsArray]
          if (members.forall(isSimple)) {
            // array is empty, or every member is simple
            println("this is an array with simple types")
          } else {
            // array contains at least one array or object
            println("this is an array with objects")
          }
          arr
        case _ => JsArray(Array(json))
      }