0

以下面的 JSON 字符串为例:

val document = """{
    "id": "12345",
    "createdTime": "13332517",
    "data": {
        "status": "active",
        "createdTime": "13345178"
    }"""

该字段createdTime在文档中定义了两次。返回createdTime顶层的方法是:

val createdTime = Json.parse(document \ "createdTime")

取以下 JSON 字符串;它与第一个示例相同,但现在是一个数组:

val document1 = """[{
    "id": "12345",
    "createdTime": "13332517",
    "data": {
        "status": "active",
        "createdTime": "13345178"
    }
}, {
    "id": "67890",
    "createdTime": "13332565",
    "data": {
        "status": "active",
        "createdTime": "13345173"
    }
}]"""

递归返回“createdTime”定义为:

val createdTime1 = Json.parse(document1) \\ "createdTime"

但是,这也会返回嵌套createdTime字段。有没有办法只递归返回顶层createdTime

4

1 回答 1

1

当您解析document1并将其转换为 时JsArray,您应该有一个数组。然后您可以迭代该值map以获取顶层 createdTime。

val createdTimes = Json.parse(document1).as[JsArray].value.map(_ \ "createdTime")

于 2017-10-03T11:41:06.207 回答