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

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

问题描述

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

<代码>{"name":"@收藏夹","description":"我最喜欢的地方的集合",list_id":4894636,}

一个响应将包含许多部分,就像上面的例子一样.

我想在 Jmeter 中做的是通过 JSON 响应并以一种方式提取上面概述的每个部分,以便我可以将返回的名称和描述作为一个条目进行迭代.

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

有谁知道在这个例子中我如何使用正则表达式提取多个值?

解决方案

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

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

JSON 响应处理可以使用 BeanShell 脚本(~java)+任何 json 处理库(例如 json-rpc-1.0):
- 在 BeanShell SamplerBeanShell PostProcessor;
- 当前默认提供了所有必需的 beanshell 库jmeter交付;
- 使用 json 处理库将 jar 放入 JMETER_HOME/lib 文件夹.

示意图如下:

  1. 如果是 BeanShell 后处理器:

    <前>线程组...您的 HTTP 请求BeanShell PostProcessor//添加为子项...

  2. 如果是 BeanShell 采样器:

    <前>线程组...您的 HTTP 请求BeanShell Sampler//添加单独的采样器 - 在您之后...

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

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

采样代码:

import java.io.*;导入 java.util.*;导入 org.json.*;导入 org.apache.jmeter.samplers.SampleResult;ArrayList nodeRefs = new ArrayList();ArrayList 文件名 = new ArrayList();String ExtractedList = "extracted.csv";StringBuilder 内容 = new StringBuilder();尝试{if (ctx.getPreviousResult().getResponseDataAsString().equals("")) {失败=真;FailureMessage = "错误:响应为空.";throw new Exception("错误:响应为空.");} 别的 {if ((ResponseCode != null) && (ResponseCode.equals("200") == true)) {SampleResult 结果 = ctx.getPreviousResult();JSONObject response = new JSONObject(result.getResponseDataAsString());FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir") + File.separator + ExtractList);如果(响应.有(项目")){JSONArray items = response.getJSONArray("items");如果 (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");如果(我!= 0){content.append("
");}contents.append(name).append(",").append(description).append(",").append(list_id);System.out.println("	" + 名称 + "		" + 描述 + "		" + list_id);}}}byte [] buffer = contents.toString().getBytes();fos.write(缓冲区);fos.close();} 别的 {失败=真;FailureMessage = "无法从 JSON 响应中提取.";}}}捕获(异常前){IsSuccess = false;log.error(ex.getMessage());System.err.println(ex.getMessage());}抓住(可扔的){System.err.println(thex.getMessage());}

还有一组关于此的链接:

<小时>

更新.2017 年 8 月:

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

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.

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.

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?

解决方案

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

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 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. in case of BeanShell PostProcessor:

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

  2. 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.

Sampler code:

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("
");
                        }

                        contents.append(name).append(",").append(description).append(",").append(list_id);
                        System.out.println("	 " + name + "		" + description + "		" + 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());
}

As well a set of links on this:


Upd. on 08.2017:

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

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

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