如何提取json路径并找到数组长度?

时间:2017-04-20 12:58:26

标签: java arrays json jmeter

如何使用java提取JSON路径并查找数组长度?我的以下回复数据。我需要在Jmeter断言中验证数组长度应该等于'7'。

$data = array("country"=>"US","states"=>array("MHASASAS"=>"MH","XYZABABA"=>"XYZ"));
$postdata = json_encode($data);

$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);

1 个答案:

答案 0 :(得分:3)

  1. 添加JSON Extractor作为产生上述JSON响应的请求的子代,并按如下方式对其进行配置:

    • 变量名称:任何有意义的名称,即week
    • JSON路径表达式:$[*]
    • 比赛号码:-1

      JMeter JSON Extractor

    这将生成以下JMeter变量(您可以使用Debug Sampler验证它们):

    week_1=["Week","Event Count"]
    week_2=["3\/13\/17","1"]
    week_3=["3\/20\/17","1"]
    week_4=["3\/27\/17","1"]
    week_5=["4\/3\/17","1"]
    week_6=["4\/10\/17","1"]
    week_7=["4\/17\/17","1"]
    week_matchNr=7
    

    你对后者特别感兴趣

    JMeter Debug Sampler

  2. Response Assertion添加为同一请求的子项,并按如下方式对其进行配置:

    • 适用于:JMeter变量 - > week_matchNr
    • 模式匹配规则:Equals
    • 要测试的模式:7

    JMeter Response Assertion Against JSON Variable

    这样,如果匹配数等于7,您的采样器将通过,否则将失败。有关在JMeter测试中使用断言的详细信息,请参阅How to Use JMeter Assertions in Three Easy Steps文章。