JMET JSON фильтр данных на основе условия - PullRequest
0 голосов
/ 28 августа 2018

Я работаю над jmeter и пытаюсь получить значения из ответа Json. У меня ниже Json:

`{
  "linked": {},
  "learning_items": [
    {
      "id": "3452",
      "enrollable_id": "3452",
      "enrollable_type": "Enrollment",
      "learnable_id": "6",
      "learnable_type": "CourseTemplate",
      "title": "all kinda ",
      "description": "",
      "state": "created",
      "completed_at": null,
      "created_at": "2017-04-10T16:26:36.850-06:00",
      "archived_at": null,
      "permanently_failed": false,
      "data": {
        "end_at": "2017-04-16T23:59:59.000-06:00",
        "expires_at": null,
        "renew_by": null,
        "required": true,
        "score": 0,
        "time_remaining": 5,
        "current_position": 0,
        "furthest_progress": 0,
        "quiz_positions": [
          2,
          3,
          4,
          5
        ],
        "direct_enrollment": true,
        "max_quiz_attempts": null,
        "attempts_count": 0,
        "inactive": null,
        "program": null,
        "programs": [],
        "in_completed_program": false,
        "external_id": null,
        "estimated_time": 5,
        "passing_threshold": 80,
        "has_certificate": false,
        "course_type": "bridge",
        "slide_count": 5,
        "attachments_count": 1,
        "attachments_count_author": 2,
        "third_party_course_id": null,
        "open_book": true,
        "continuing_education_credits": null,
        "features": [
          "has_quizzes"
        ]
      },
      "tags": []
    },
    {
      "id": "3451",
      "enrollable_id": "3451",
      "enrollable_type": "Enrollment",
      "learnable_id": "7",
      "learnable_type": "CourseTemplate",
      "title": "All types",
      "description": "",
      "state": "active",
      "completed_at": null,
      "created_at": "2017-04-10T16:26:36.605-06:00",
      "archived_at": null,
      "permanently_failed": false,
      "data": {
        "end_at": "2017-04-17T23:59:59.000-06:00",
        "expires_at": null,
        "renew_by": null,
        "required": true,
        "score": 0,
        "time_remaining": 7,
        "current_position": 1,
        "furthest_progress": 0.1429,
        "quiz_positions": [
          2,
          3,
          4,
          5,
          6,
          7
        ],
        "direct_enrollment": true,
        "max_quiz_attempts": null,
        "attempts_count": 1,
        "inactive": null,
        "program": null,
        "programs": [],
        "in_completed_program": false,
        "external_id": null,
        "estimated_time": 7,
        "passing_threshold": 80,
        "has_certificate": false,
        "course_type": "bridge",
        "slide_count": 7,
        "attachments_count": 0,
        "attachments_count_author": 1,
        "third_party_course_id": null,
        "open_book": false,
        "continuing_education_credits": null,
        "features": [
          "has_quizzes"
        ]
      },
      "tags": []
    },
    {
      "id": "6301",
      "enrollable_id": "1",
      "enrollable_type": "ProgramEnrollment",
      "learnable_id": "1",
      "learnable_type": "Program",
      "title": "IamaProgram",
      "description": null,
      "state": "active",
      "completed_at": null,
      "created_at": "2018-08-27T13:01:07.383-06:00",
      "archived_at": null,
      "permanently_failed": false,
      "data": {
        "required": true,
        "current_course": {
          "id": 19,
          "title": "abcde",
          "state": "created",
          "end_at": "2018-09-03T23:59:59.999-06:00",
          "expires_at": null,
          "renew_by": null,
          "required": true,
          "score": 0,
          "estimated_time": 2,
          "time_remaining": 2,
          "passing_threshold": 80,
          "has_certificate": null,
          "course_type": "bridge",
          "slide_count": 2,
          "attachments_count": 0,
          "current_position": 0,
          "furthest_progress": 0,
          "learnable_type": "CourseTemplate"
        },
        "end_at": null,
        "expires_at": null,
        "furthest_progress": 0,
        "inactive": null,
        "item_count": 2,
        "item_counts": [
          {
            "item_type": "CourseTemplate",
            "count": 2
          }
        ],
        "program_index": 1,
        "has_certificate": false,
        "pending_approval_item_count": 0,
        "pending_approval_items": [],
        "features": [
          "has_quizzes"
        ]
      },
      "tags": []
    },
    {
      "id": "6300",
      "enrollable_id": "1",
      "enrollable_type": "TaskEnrollment",
      "learnable_id": "1",
      "learnable_type": "Task",
      "title": "IamaCheckpoint",
      "description": "",
      "state": "created",
      "completed_at": null,
      "created_at": "2018-08-27T12:59:42.541-06:00",
      "archived_at": null,
      "permanently_failed": false,
      "data": {
        "requires_approval": false,
        "requires_evidence": false,
        "direct_enrollment": true,
        "required": true,
        "program": null,
        "programs": [],
        "in_completed_program": false,
        "end_at": "2018-09-03T23:59:59.999-06:00",
        "inactive": null,
        "attachments_count": 0,
        "attachments_count_author": 0,
        "has_certificate": false
      },
      "tags": []
    },
    {
      "id": "3450",
      "enrollable_id": "3450",
      "enrollable_type": "Enrollment",
      "learnable_id": "4",
      "learnable_type": "CourseTemplate",
      "title": "Science 101",
      "description": null,
      "state": "complete",
      "completed_at": "2018-08-27T12:37:13.365-06:00",
      "created_at": "2017-04-10T16:26:36.368-06:00",
      "archived_at": null,
      "permanently_failed": false,
      "data": {
        "end_at": "2017-04-17T23:59:59.000-06:00",
        "expires_at": null,
        "renew_by": null,
        "required": true,
        "score": 100,
        "time_remaining": 0,
        "current_position": 0,
        "furthest_progress": 1,
        "quiz_positions": [],
        "direct_enrollment": true,
        "max_quiz_attempts": null,
        "attempts_count": 1,
        "inactive": null,
        "program": null,
        "programs": [],
        "in_completed_program": false,
        "external_id": null,
        "estimated_time": 4,
        "passing_threshold": 80,
        "has_certificate": false,
        "course_type": "bridge",
        "slide_count": 4,
        "attachments_count": 0,
        "attachments_count_author": 0,
        "third_party_course_id": null,
        "open_book": null,
        "continuing_education_credits": null,
        "features": []
      },
      "tags": []
    }
  ],
  "meta": {}
}`

Я просто хочу получить все курсы (learnable_id), которые

  • Состояние = Создано
  • learnable_type = CourseTemplate

Как только я получу все learnable_id, которые удовлетворяют вышеуказанному условию, я могу вернуть случайное число из этого массива.

Как мне это получить?

Заранее спасибо.

Ответы [ 2 ]

0 голосов
/ 29 августа 2018

Вы можете использовать путь JSON для извлечения значений ключей JSON, применяя необходимые фильтры

Добавьте JSON экстрактор в качестве дочернего элемента вашего запроса, когда вы получаете выше респон.

использовать следующую конфигурацию в экстракторе JSON

 Json path Expression :  $..[?(@.learnable_type=='CourseTemplate' && @.state == 'created')].learnable_id

match no : 0 (Это вернет случайное совпадение из возможных совпадений в JMeter

как показано ниже enter image description here

Результат отладки:

enter image description here

Дополнительная информация: Извлечение переменных

0 голосов
/ 28 августа 2018
    import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import org.apache.commons.lang.StringUtils;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;


//Get Store total count
int totalLearningItems = StringUtils.countMatches(new String(data), "enrollable_id");
log.info("Total Number of Learning Items are: " + totalLearningItems);
Random rand = new Random();

if (totalLearningItems > 0) {
    //Check for Fulfilment type is "Pickup"
    String jsonString = new String(data);
    JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
    JSONObject learning_items = (JSONObject) parser.parse(data);
    JSONArray learningArray = (JSONArray) learning_items.get("learning_items");
    String learningItemId;
    courseList = new ArrayList();
    programList = new ArrayList();
    taskList = new ArrayList();

    for (int i=0; i<learningArray.size(); i++) {

            if(learningArray.get(i).getAsString("state").equals("created") || learningArray.get(i).getAsString("state").equals("active")) {
                if(learningArray.get(i).getAsString("learnable_type").equals("CourseTemplate")){
                courseList.add(learningArray.get(i).getAsString("learnable_id"));
                } else if (learningArray.get(i).getAsString("learnable_type").equals("Program")) {
                    programList.add(learningArray.get(i).getAsString("learnable_id"));
                } else if (learningArray.get(i).getAsString("learnable_type").equals("Task")) {
                    taskList.add(learningArray.get(i).getAsString("learnable_id"));
                }               
            }             
    }

    if(courseList.size() > 0) {
        vars.put("courseID", courseList.get(new Random().nextInt(courseList.size())));
    } else if (programList.size() > 0) {
        vars.put("programID", programList.get(new Random().nextInt(programList.size())));
    } else if(taskList.size() > 0) {
        vars.put("taskID", taskList.get(new Random().nextInt(taskList.size())));            
    }     
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...