【问题标题】:Non-recursive extraction in Lift JSON for-comprehensionLift JSON 中的非递归提取以便于理解
【发布时间】:2012-03-05 00:47:09
【问题描述】:

我正在使用 Lift JSON 的 for-comprehensions 来解析一些 JSON。 JSON是递归的,例如字段id 存在于每个级别。这是一个例子:

val json = """
{
  "id": 1
  "children": [
    {
      "id": 2
    },
    {
      "id": 3
    }
  ]
}
"""

以下代码

var ids = for {
  JObject(parent) <- parse(json)
  JField("id", JInt(id)) <- parent
} yield id

println(ids)

产生List(1, 2, 3)。我期待它能够生产List(1)

在我的程序中,这会导致二次计算,尽管我只需要线性。

是否可以使用 for-comprehensions 仅匹配* id 字段?

【问题讨论】:

    标签: scala lift for-comprehension lift-json


    【解决方案1】:

    我还没有深入研究为什么默认理解是递归的,但是您可以通过简单地限定搜索根来解决这个问题:

    scala>  for ( JField( "id", JInt( id ) ) <- parent.children ) yield id
    res4: List[BigInt] = List(1)
    

    注意parent.children的使用。

    【讨论】: