I need to write a function that recieve JsValue, and do those steps:
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!
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
}
- if its NOT Array, return the value inside a list
def myFunc(json: JsValue): JsArray =
json match {
case JsArray(members) => ???
case _ => JsArray(Array(json))
}
- if its Array of simple type return this Array and print "this is an array with simple types"
- 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))
}