2

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!

cchantep
  • 9,118
  • 3
  • 30
  • 41
JohnBigs
  • 2,691
  • 3
  • 31
  • 61
  • What if it contains both objects and simple types? What if it contains things other than objects or simple types (e. g. arrays, functions)? – Matthias Berndt Nov 17 '21 at 12:57

2 Answers2

2

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))
  }
Levi Ramsey
  • 18,884
  • 1
  • 16
  • 30
0

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.

Tausif Sayyad
  • 248
  • 1
  • 9