arrays - 数组长度的 Jsonpath

标签 arrays groovy size spock jsonpath

给定 json,例如

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

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

我已经使用谷歌代码的 JsonPath 库进行了几次尝试,请注意:
JsonPath.read(json, "arr1.length")

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

我正在寻找解析为数组长度的单个字符串路径,而不是对中间的后续调用,例如
JsonPath.read(json, "arr1").length // useless to me

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

对于上下文,我想提供带有路径/值对的测试套件,这对值非常有用,但我无法使用此模式断言数组大小。

最佳答案

如果仅在断言时需要数组的长度,则 json-path-assert神器可以和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's Matcher API这为灵活和广泛的断言打开了大门。

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

关于arrays - 数组长度的 Jsonpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24775754/

相关文章:

arrays - Swift:将两个数组匹配成一个数组

c# - C#中的常量数组

集合中的 Grails 域类

c++ - 当大小增加时编译数组数组时崩溃

arrays - 遥控接口(interface): Passing multidimensional arrays

groovy - 使用 Spock 验证非 spy 方法调用

mysql - 用于 sql 的 Groovy groupby 或映射

在 C 中将多个字节转换为文件大小

iphone - 为 UITabViewController 设置自定义设计尺寸(在 Storyboard 中)

javascript - 在 JavaScript 中显示分组项目