6

给定json,例如

{"arr1" : [1,2,3], "arr2" : []}

已知有名为 arr1 和 arr2 的数组,是否有长度的 jsonpath 表达式适用于空数组和非空数组的数组

值得注意的是,我使用谷歌代码的 JsonPath 库进行了几次尝试:

JsonPath.read(json, "arr1.length")

但它给出了一个错误,说数组没有属性。

我正在寻找解析为数组长度的单个字符串路径,而不是对中间体的后续调用,例如

JsonPath.read(json, "arr1").length // useless to me

任何复杂程度的表达都是可以接受的。

对于上下文,我想为测试套件提供路径/值对,这对值很有用,但我不能用这种模式断言数组大小。

4

2 回答 2

8

如果仅断言需要数组的长度,则json-path-assert可以将 artifact 与 结合使用JsonPath。这是一个用 Groovy 编写的示例:

@Grab('com.jayway.jsonpath:json-path:0.9.1')
@Grab('com.jayway.jsonpath:json-path-assert:0.9.1')

import com.jayway.jsonpath.JsonPath
import static com.jayway.jsonassert.JsonAssert.*
import static org.hamcrest.MatcherAssert.assertThat
import static org.hamcrest.Matchers.*

def json = /{ "arr1": [1,2,3], "arr2": [] }/

with(json).assertThat( "arr1", hasSize(3) )
          .assertThat( "arr2", hasSize(0) )
          .assertThat( "arr2", emptyCollection() )

验证断言是否因数组大小不同而失败。最好的部分是使用Hamcrest 的 Matcher API,它为灵活多样的断言打开了大门。

无法从路径表达式 AFAIK 中获取长度。

于 2014-07-16T15:02:42.650 回答
1

@dmahapatro 说得对

无法从路径表达式中获取长度

但是,如果您只需要它来访问某些特定元素(比如说数组的最后一个元素),您仍然可以使用:

{"arr1": [1,2,3], "arr2": [{"name": "a"}, {"name": "b"}]}
arr1[(@.length-1)]       // returns "3"
arr2[(@.length-1)].name  // returns "b"

您还可以执行更高级的请求,但我建议您查看插件的文档

于 2015-09-18T15:08:56.370 回答