简体   繁体   中英

How to parse JSON in Jmeter using Java or Groovy

I have a problem with JSON parsing in Jmeter. This is a response

{
  "data": [
    {
      "_id": "6138b66a-83df-4860-8327-62f942e0e9b3",
      "artifactory_repo": {
        "maven-snapshot-repo": ""
      },
      "created_by": "system",
      "created_date": "2018-04-17T10:45:55",
      "created_request_id": "",
      "description": "",
      "git_repo": {
        "https://github.com/Leela-Padmaja/example-java-maven.git": ""
      },
      "id": "6138b66a-83df-4860-8327-62f942e0e9b3",
      "jobs": {
        "clone-MavenEx": "http://101.707.106.99:803/job/clone-MavenEx/1/"
      },
      "name": "Test1",
      "pattern": {
        "exclude": [],
        "include": []
      },
      "services": {
        "0727a49a-6c95-433e-9fc5-7e5c760cc76f": {
          "builds": {
            "clone-MavenEx": {
              "last_retrieved": "2018-04-19T11:00:01.011Z"
            }
          }
        }
      },
      "updated_by": "system",
      "updated_date": "2018-04-19T11:00:03",
      "updated_request_id": ""
    },

I need to get build name for particular _id value. For sample above is clone-MavenEx without anything else. The _id value I got previously using JSON Extractor.

I used the following Groovy code in JSR223 Post Processor

import org.apache.jmeter.samplers.SampleResult; 
import groovy.json.JsonSlurper;

String jsonString = prev.getResponseDataAsString();
String projectID = vars.get("project_id");

def slurper = new JsonSlurper();
def result  = slurper.parseText(jsonString);
def index   = result.find { it._id == projectID };

if ( index == null ) {
    vars.put( "buildName", 'NOTFOUND' );
} else {
    vars.put( "buildName", index.builds.toString() );
}

As per JMeter Best Practices it is recommended to use JMeter Test Elements and avoid scripting where possible. My expectation is that you can get everything you need using JSON Extractor

The relevant JSON Path query would be something like:

$.data[?(@._id == '6138b66a-83df-4860-8327-62f942e0e9b3')].services[*].builds 

Demo:

JMeter JSON提取器

If you want you can replace hard-coded project id with the relevant JMeter Variable:

$.data[?(@._id == '${project_id}')].services[*].builds

Full equivalent configuration:

JMeter JSON提取器

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM