lift-json XPath \\运算符具有不同的返回类型,具体取决于num匹配

时间:2014-02-13 18:13:29

标签: scala xpath lift lift-json json4s

我希望json \\ "something"总是返回相同类型的对象(或者至少是一些总是同构的)对于具有相同模式的数据的相同查询,但是,请考虑:

val json1 = ("people" -> List(
  ("person" -> ("name" -> "Joe")),
  ("person" -> ("name" -> "Marilyn"))))

val json2 = ("people" -> List(
  ("person" -> ("name" -> "Joe"))))

val json3 = ("people" -> List[(String, String)]())

println((json1 \\ "name")) // JObject(List(JField(name,JString(Joe)), JField(name,JString(Marilyn))))
println((json2 \\ "name")) // JString(Joe)
println((json3 \\ "name")) // JObject(List())

// which causes the following construction to sometimes fail
println((json1 \\ "name").children map { case JField(_, JString(name)) => name })
// List(Joe, Marilyn)
println((json2 \\ "name").children map { case JField(_, JString(name)) => name })
// List()  !!!!!
println((json3 \\ "name").children map { case JField(_, JString(name)) => name })
// List()

...所以n = 0和n> = 2个案例是一致处理的,但n = 1个特殊情况JValue

为什么会这样?这是设计吗?

List

上的映射进行比较
val people = List(Person(name = "Joe"), Person(name = "Mary"))
people.map(_.name) # => returns a List

val people = List(Person(name = "Joe"))
people.map(_.name) # => returns a List

val people = List()
people.map(_.name) # => returns a List

与Scala的XML进行比较

val xml1 = <people> <person><name>Joe</name></person> <person><name>Marylin</name></person> <person><name>Erik</name></person> </people>
val xml2 = <people> <person><name>Erik</name></person> </people>
val xml3 = <people> </people>

Seq(xml1, xml2, xml3).map(_ \\ "name") foreach (x => println(s"${x.getClass}\t${x.length}\t$x"))

// OUTPUT:    
// class scala.xml.NodeSeq$$anon$1  3   <name>Joe</name><name>Marylin</name><name>Erik</name>
// class scala.xml.NodeSeq$$anon$1  1   <name>Erik</name>
// class scala.xml.NodeSeq$$anon$1  0   

那么为什么不应该期望lift-json \\运算符具有相同的语义?

http://liftweb.net/api/26/api/#net.liftweb.json.package的文档有:

  

类似XPath的表达式,用于按名称查询 JSON字段。返回所有匹配的字段。

1 个答案:

答案 0 :(得分:1)

在Json4s \\现在总是返回JArray,请参阅here

val json1 =
  parse("""
    |{
    |  "people": [{
    |    "name": "Joe"
    |  }, {
    |    "name": "Marilyn"
    |  }]
    |}
  """.stripMargin)

val json2 =
  parse("""
    |{
    |  "people": [{
    |    "name": "Joe"
    |  }]
    |}
  """.stripMargin)


println(json1 \\ "name")
// JArray(List(JString(Joe), JString(Marilyn)))

println(json2 \\ "name")
// JArray(List(JString(Joe)))