gpt4 book ai didi

arrays - 数组长度的 Jsonpath

转载 作者:行者123 更新时间:2023-12-04 14:12:50 26 4
gpt4 key购买 nike

给定 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com