使用RegEx Extractor从JSON响应中提取多个值 [英] Pulling multiple values from JSON response using RegEx Extractor

查看:362
本文介绍了使用RegEx Extractor从JSON响应中提取多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试一个返回JSON响应的Web服务,我想从响应中提取多个值.典型的响应将在列表中包含多个值.例如:

I'm testing a web service that returns JSON responses and I'd like to pull multiple values from the response. A typical response would contain multiple values in a list. For example:

{
"name":"@favorites",
"description":"Collection of my favorite places",
"list_id":4894636,
}

响应将包含与上面的示例类似的许多部分.

A response would contain many sections like the above example.

我想在Jmeter中进行的工作是遍历JSON响应,并以一种可以将返回的名称和描述作为一个条目进行迭代的方式拉出上面概述的每个部分.

What I'd like to do in Jmeter is go through the JSON response and pull each section outlined above in a manner that I can tie the returned name and description as one entry to iterate over.

到目前为止,我能做的就是使用模板$ 1 $用正则表达式提取器("name":(.+?)")返回名称值.我想同时使用名称和描述,但似乎无法使用它.我尝试过使用带有$ 1 $$ 2 $模板的正则表达式"name":(.+?)","description":(.+?)",但未成功.

What I've been able to do thus far is return the name value with regular expression extractor ("name":"(.+?)") using the template $1$. I'd like to pull both name and description but can't seem to get it to work. I've tried using a regex "name":"(.+?)","description":"(.+?)" with a template of $1$$2$ without any success.

有人知道在此示例中如何使用正则表达式提取多个值吗?

Does anyone know how I might pull multiple values using regex in this example?

推荐答案

可能值得使用 BeanShell脚本处理JSON响应.

It may be worth to use BeanShell scripting to process JSON response.

因此,如果您需要从响应中获得所有名称/描述"对(针对每个部分),则可以执行以下操作:
1.从循环响应中提取所有名称/描述"对;
2.以方便的格式将提取的对保存在csv文件中;
3.稍后在代码中使用 CSV数据集配置,从csv文件中读取已保存的对. a>循环播放,例如

So if you need to get ALL the "name/description" pairs from response (for each section) you can do the following:
1. extract all the "name/description" pairs from response in loop;
2. save extracted pairs in csv-file in handy format;
3. read saved pairs from csv-file later in code - using CSV Data Set Config in loop, e.g.

JSON响应处理可以使用BeanShell脚本(〜java)+任何json处理库(例如 BeanShell采样器中或在

JSON response processing can be implemented using BeanShell scripting (~ java) + any json-processing library (e.g. json-rpc-1.0):
- either in BeanShell Sampler or in BeanShell PostProcessor;
- all the required beanshell libs are currently provided in default jmeter delivery;
- to use json-processing library place jar into JMETER_HOME/lib folder.

从原理上看,它看起来像:

Schematically it will look like:

  1. 对于BeanShell PostProcessor:

  1. in case of BeanShell PostProcessor:


Thread Group
    . . .
    YOUR HTTP Request
        BeanShell PostProcessor    // added as child
    . . .

  • 对于BeanShell Sampler:

  • in case of BeanShell Sampler:

    
    Thread Group
        . . .
        YOUR HTTP Request
        BeanShell Sampler          // added separate sampler - after your
        . . .
    

  • 在这种情况下,使用哪一个没有区别.

    In this case there is no difference which one use.

    您可以将代码本身放入采样器主体(脚本"字段)中,也可以存储在外部文件中,如下所示.

    You can either put the code itself into the sampler body ("Script" field) or store in external file, as shown below.

    采样代码:

    import java.io.*;
    import java.util.*;
    import org.json.*;
    import org.apache.jmeter.samplers.SampleResult;
    
    ArrayList nodeRefs = new ArrayList();
    ArrayList fileNames = new ArrayList();
    
    String extractedList = "extracted.csv";
    StringBuilder contents = new StringBuilder();
    
    try
    {
        if (ctx.getPreviousResult().getResponseDataAsString().equals("")) {
            Failure = true;
            FailureMessage = "ERROR: Response is EMPTY.";
            throw new Exception("ERROR: Response is EMPTY.");
        } else {
            if ((ResponseCode != null) && (ResponseCode.equals("200") == true)) {
                SampleResult result = ctx.getPreviousResult();    
                JSONObject response = new JSONObject(result.getResponseDataAsString());
    
                FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir") + File.separator + extractedList);
    
                if (response.has("items")) {
                    JSONArray items = response.getJSONArray("items");
    
                    if (items.length() != 0) {
                        for (int i = 0; i < items.length(); i++) {
                            String name = items.getJSONObject(i).getString("name");
                            String description = items.getJSONObject(i).getString("description");
                            int list_id = items.getJSONObject(i).getInt("list_id");
    
                            if (i != 0) {
                                contents.append("\n");
                            }
    
                            contents.append(name).append(",").append(description).append(",").append(list_id);
                            System.out.println("\t " + name + "\t\t" + description + "\t\t" + list_id);
                        }
                    }                                       
                }
    
                byte [] buffer = contents.toString().getBytes();    
    
                fos.write(buffer);
                fos.close();
            } else {
                Failure = true;
                FailureMessage = "Failed to extract from JSON response.";
            }
        }
    }
    catch (Exception ex) {
        IsSuccess = false;
        log.error(ex.getMessage());
        System.err.println(ex.getMessage());
    }
    catch (Throwable thex) {
        System.err.println(thex.getMessage());
    }
    

    与此有关的一组链接:

    • JSON in JMeter
    • Processing JSON Responses with JMeter and the BSF Post Processor

    已更新.于08.2017:

    目前,JMeter已设置了一组内置组件(从第3方项目中合并)来处理JSON,而无需编写脚本:

    At the moment JMeter has set of built-in components (merged from 3rd party projects) to handle JSON without scripting:

    • JSON Path Extractor (contributed from ATLANTBH jmeter-components project);
    • JSON Extractor (contributed from UBIK Load Pack since JMeter 3.0) - see answer below.

    这篇关于使用RegEx Extractor从JSON响应中提取多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆