JsonPath使用教程

application/json标识Json数据格式,是Http请求常见的一种Content-Type。我们经常也会看到接口返回数据类型为json格式。功能测试/自动化脚本里,经常会需要提取json数据,用作上下文使用或者用作断言校验。使用JsonPath可以很好的完成对Json的提取使用

Jmeter的JsonPath提取器

JSON提取器说明

Apply to:应用范围
Names of created variables :接收值的变量名,自定义,多个变量用分号分隔 
JSON Path expression: json path表达式,也是用分号分隔 
Match No.(0 for Random):0表示随机;n取第几个匹配值;-1匹配所有。若只要获取到匹配的第一个值,则填写1
Compute concatenation var(suffix_ALL):如果找到许多结果,则插件将使用' , '分隔符将它们连接起来,并将其存储在名为<variable name> _ALL的var中
Default Values: 缺省值,匹配不到值的时候取该值,可写error。

如何编写JsonPath

  1. 基本语法
    image

  2. 使用示例

$.store.book[*].author	获取json中store下book下的所有author值
$..author	获取所有json中所有author的值
$.store.*	所有的东西,书籍和自行车
$.store..price	获取json中store下所有price的值
$..book[2]	获取json中book数组的第3个值
$..book[-2]	倒数的第二本书
$..book[0,1]	前两本书
$..book[:2]	从索引0(包括)到索引2(排除)的所有图书
$..book[1:2]	从索引1(包括)到索引2(排除)的所有图书
$..book[-2:]	获取json中book数组的最后两个值
$..book[2:]	获取json中book数组的第3个到最后一个的区间值
$..book[?(@.isbn)]	获取json中book数组中包含isbn的所有值
$.store.book[?(@.price < 10)]	获取json中book数组中price<10的所有值
$..book[?(@.price <= $['expensive'])]	获取json中book数组中price<=expensive的所有值
$..book[?(@.author =~ /.*REES/i)]	获取json中book数组中的作者以REES结尾的所有值(REES不区分大小写)
$..*	逐层列出json中的所有值,层级由外到内
$..book.length()	获取json中book数组的长度

官网给出的Json示例

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

Java的JsonPath工具包

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>
类似Jar不仅仅这一个

Python的JsonPath工具包

import jsonpath

扫一扫,关注我

posted @ 2020-09-18 22:16  老僧观天下  阅读(1429)  评论(0编辑  收藏  举报