Home > Net >  How to check if JsArray holds Objects or Simple types?
How to check if JsArray holds Objects or Simple types?

Time:11-19

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!

CodePudding user response:

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

CodePudding user response:

You can use the validate method, please refer to this document https://www.playframework.com/documentation/2.8.x/ScalaJson You will get multiple approaches here using validation is one of them and preferable too.

val input = """{
                |       "a": "1233"
                |   }""".stripMargin

  val json = Json.parse(input)
  json.validate[JsArray].map(println).getOrElse(println(json))

Here if JSON is of the JsArray it will go into the map function otherwise (getOrElse) it will simply print the whatever JSON value it has.

  • Related