Reputation: 3395
I'm using Lift JSON's for-comprehensions to parse some JSON. The JSON is recursive, so e.g. the field id
exists at each level. Here is an example:
val json = """
{
"id": 1
"children": [
{
"id": 2
},
{
"id": 3
}
]
}
"""
The following code
var ids = for {
JObject(parent) <- parse(json)
JField("id", JInt(id)) <- parent
} yield id
println(ids)
produces List(1, 2, 3)
. I was expecting it to product List(1)
.
In my program this results in quadratic computation, though I only need linear.
Is it possible to use for-comprehensions to match the top level id
fields only?
Upvotes: 1
Views: 313
Reputation: 4112
I haven't delved deep enough to figure out why the default comprehension is recursive, however you can solve this by simply qualifying your search root:
scala> for ( JField( "id", JInt( id ) ) <- parent.children ) yield id
res4: List[BigInt] = List(1)
Note the use of parent.children.
Upvotes: 1