Take the following JSON string as an example:
val document = """{
"id": "12345",
"createdTime": "13332517",
"data": {
"status": "active",
"createdTime": "13345178"
}"""
The field createdTime
is defined twice in the document.
To return the createdTime
at the top layer is done by:
val createdTime = Json.parse(document \ "createdTime")
Take the following JSON string; it is the same as the first example, but it is now an array:
val document1 = """[{
"id": "12345",
"createdTime": "13332517",
"data": {
"status": "active",
"createdTime": "13345178"
}
}, {
"id": "67890",
"createdTime": "13332565",
"data": {
"status": "active",
"createdTime": "13345173"
}
}]"""
To recursively return "createdTime" is defined as:
val createdTime1 = Json.parse(document1) \\ "createdTime"
However this also returns the nested createdTime
fields. Is there a way to recursively return only the top layer createdTime
?
When you parse the document1
and cast it to JsArray
, you should have an array. Then you can iterate on the value with map
to get the top layer createdTime's.
val createdTimes = Json.parse(document1).as[JsArray].value.map(_ \ "createdTime")