How can I count the number of JsObjects in a JsValue?

In Game! (2.2-M2) I have a JsValue similar to:

val people: JsValue = [{"name":"Alice","subdomain":"alice","color":"orange"},{"name":"Jorge","subdomain":"jorge","color":"blue"},{"name":"Bob","subdomain":"robert","color":"green"}...] 

I just need the number of elements in this JsValue. I can get it, clunkily, through

 (people \\ "name").size 

but the calculation of this size is inside the method, which receives JsValues ​​with different content, and name will not always be present, for example

 val places: JsValue = [{"country":"UK", "country":"ES", ...] 

or

 val things: JsValue = [{"widget":"foo", "price":"1", "widget":"bar" ... ] 

I am pulling my hair, how can I just get the number of elements in these JsValues?

+8
source share
1 answer

If you want to count the number of objects inside an array, you can match it with JsArray .

people.as[JsArray].value.size or people.as[JsArray].value.size people.asOpt[JsArray].map(_.value.size) .

+22
source share

All Articles