jsonpath(xpath for json)

接口测试中,面对复杂的JSON返回结果,JSONPath作为一种类似于XPath的语法,提供了更便捷的方式来提取元素。它能简化深层级JSON数据的访问,提高断言效率。本文通过对比XPath和JSONPath,介绍JSONPath的运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在接口测试中,我们需要断言接口的返回结果,若返回结果是json格式,就要一层一层的取json中的元素(r.json()[store][book][category]);若json层级较深,表达式就会很长。而jsonpath为我们提供了更加灵活、方便的获取元素的方式,下面举例说明jsonpath的使用。

官网地址:https://goessner.net/articles/JsonPath/

from jsonpath import jsonpath

book_dict = {
    "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
        }
    }
}

#store.book下所有的author值
print(jsonpath(book_dict, '$.store.book[*].author'))

# 所有author的值
print(jsonpath(book_dict, '$..author'))

# store中所有的value
print(jsonpath(book_dict, '$.store.*'))

# store下所有price的值
print(jsonpath(book_dict, '$.store..price'))

# book中第3个元素
print(jsonpath(book_dict, '$..book[2]'))

# book中最后1个元素
print(jsonpath(book_dict, '$..book[(@.length-1)]'))
print(jsonpath(book_dict, '$..book[-1:]'))

# book中前两个元素
print(jsonpath(book_dict, '$..book[0,1]'))
print(jsonpath(book_dict, '$..book[:2]'))

# 所有含有isbn的元素
print(jsonpath(book_dict, '$..book[?(@.isbn)]'))

# 所有price小于10的元素
print(jsonpath(book_dict, '$..book[?(@.price<10)]'))

xpath与jsonpath对比

XPathJSONPathDescription
/$the root object/element
.@the current object/element
/. or []child operator
n/aparent operator
//recursive descent. JSONPath borrows this syntax from E4X.
**wildcard. All objects/elements regardless their names.
@n/aattribute access. JSON structures don’t have attributes.
[][]subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.
|[,]Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.
n/a[start:end:step]array slice operator borrowed from ES4.
[]?()applies a filter (script) expression.
n/a()script expression, using the underlying script engine.
()n/agrouping in Xpath
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值