缘由

由于之前做的测试服务,让同事们在浏览器中编写测试用例,JSON格式的
在编写上下文依赖的用例的时候,出现这样的问题,
我们希望通过 jsonpath 定位一个符合条件的结果时,不能获得我们想要的结果

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

查找节点

JsonPath.read(s, "$..book[?(@.isbn)]")
JsonPath.read(s, "$..book[?(@.isbn)][1]")

结果

"JsonPath.read(s, "$..book[?(@.isbn)]")":[{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
"JsonPath.read(s, "$..book[?(@.isbn)])[1]"":[]

从结果来看直接加 [1] 并没有用,并且尝试了类似 xpath 的语法,也不支持

解决的思路

Object isbnBookArrayObject = JsonPath.read(s, "$..book[?(@.isbn)]");
JsonPath.parse(isbnBookArrayObject.toString()).read("$.[0]"))

参考

jsonpath github
sonpath 初探


↙↙↙阅读原文可查看相关链接,并与作者交流