jmeter Json filter data based on condition - json

I am working on jmeter and trying to get values from a Json response.
I have below 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": {}
}`
I just want to get all the courses (learnable_id) which are
State = Created
learnable_type = CourseTemplate
Once I get all the learnable_id which met above condition then I can return random number from that array.
How do I get this?
Thanks in advance.

You can use JSON path to extract json key values by applying required filters
Add a JSON extractor as a child of your request where you are getting above respone.
use the following configuration in JSON extractor
Json path Expression : $..[?(#.learnable_type=='CourseTemplate' && #.state == 'created')].learnable_id
match no : 0 (This will return a random matach from the possible matches in JMeter
as shown below
Debug Sampler Result :
More info :
Extracting variables

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

Related

Is there a way to fetch needed information from JSON file in React Native

I am using a COVID-19 API (https://api.covidactnow.org/v2/counties.json?apiKey=) that records various information like number of cases and deaths in each county in USA. In my React Native app, I retrieved the user's location, and more specifically, the user's county, state and country. In this case, I have stored the user's county name in countyName. I'd like to fetch the specific cases and deaths from the JSON file depending on what is countyName is. I have a snippet of one county in the JSON file below. I was thinking I could go into the index of the array and in the actuals, and then fetch the cases and deaths.
[
{
"fips": "02013",
"country": "US",
"state": "AK",
"county": "Aleutians East Borough",
"level": "county",
"lat": null,
"locationId": "iso1:us#iso2:us-ak#fips:02013",
"long": null,
"population": 3337,
"metrics": {
"testPositivityRatio": null,
"testPositivityRatioDetails": {
"source": "other"
},
"caseDensity": 0,
"contactTracerCapacityRatio": null,
"infectionRate": 4.71887277063,
"infectionRateCI90": 1.1615979428900003,
"icuHeadroomRatio": null,
"icuHeadroomDetails": null,
"icuCapacityRatio": null,
"vaccinationsInitiatedRatio": null,
"vaccinationsCompletedRatio": 0.27509739286784535
},
"riskLevels": {
"overall": 0,
"testPositivityRatio": 4,
"caseDensity": 0,
"contactTracerCapacityRatio": 4,
"infectionRate": 3,
"icuHeadroomRatio": 4,
"icuCapacityRatio": 4
},
"actuals": {
"cases": 363,
"deaths": 2,
"positiveTests": null,
"negativeTests": null,
"contactTracers": null,
"hospitalBeds": {
"capacity": null,
"currentUsageTotal": null,
"currentUsageCovid": null,
"typicalUsageRate": null
},
"icuBeds": {
"capacity": null,
"currentUsageTotal": null,
"currentUsageCovid": null,
"typicalUsageRate": null
},
"newCases": 0,
"newDeaths": 0,
"vaccinesDistributed": null,
"vaccinationsInitiated": null,
"vaccinationsCompleted": 918,
"vaccinesAdministered": null,
"vaccinesAdministeredDemographics": null,
"vaccinationsInitiatedDemographics": null
},
"annotations": {
"cases": {
"sources": [
{
"type": "NYTimes",
"url": "https://github.com/nytimes/covid-19-data",
"name": "The New York Times"
}
],
"anomalies": []
},
"deaths": {
"sources": [
{
"type": "NYTimes",
"url": "https://github.com/nytimes/covid-19-data",
"name": "The New York Times"
}
],
"anomalies": []
},
"positiveTests": null,
"negativeTests": null,
"contactTracers": null,
"hospitalBeds": null,
"icuBeds": null,
"newCases": null,
"newDeaths": null,
"vaccinesDistributed": null,
"vaccinationsInitiated": null,
"vaccinationsCompleted": {
"sources": [
{
"type": "other",
"url": "https://covid.cdc.gov/covid-data-tracker/#county-view",
"name": "Centers for Disease Control and Prevention"
}
],
"anomalies": []
},
"vaccinesAdministered": null,
"testPositivityRatio": null,
"caseDensity": {
"sources": [
{
"type": "NYTimes",
"url": "https://github.com/nytimes/covid-19-data",
"name": "The New York Times"
}
],
"anomalies": []
},
"contactTracerCapacityRatio": null,
"infectionRate": {
"sources": [
{
"type": "NYTimes",
"url": "https://github.com/nytimes/covid-19-data",
"name": "The New York Times"
}
],
"anomalies": []
},
"infectionRateCI90": {
"sources": [
{
"type": "NYTimes",
"url": "https://github.com/nytimes/covid-19-data",
"name": "The New York Times"
}
],
"anomalies": []
},
"icuHeadroomRatio": null,
"icuCapacityRatio": null,
"vaccinationsInitiatedRatio": null,
"vaccinationsCompletedRatio": null
},
"lastUpdatedDate": "2021-04-26",
"url": "https://covidactnow.org/us/alaska-ak/county/aleutians_east_borough"
},
The response that you got from the API in JSON format is an array of objects.
To get the no of deaths and cases from the array of objects, you need to do the following:
const response= [
{
"fips": "02013",
"country": "US",
"state": "AK",
"county": "Aleutians East Borough",
"level": "county",
"lat": null,
"locationId": "iso1:us#iso2:us-ak#fips:02013",
"long": null,
"population": 3337,
"metrics": {
"testPositivityRatio": null,
"testPositivityRatioDetails": {
"source": "other"
},
"caseDensity": 0,
"contactTracerCapacityRatio": null,
"infectionRate": 4.71887277063,
"infectionRateCI90": 1.1615979428900003,
"icuHeadroomRatio": null,
"icuHeadroomDetails": null,
"icuCapacityRatio": null,
"vaccinationsInitiatedRatio": null,
"vaccinationsCompletedRatio": 0.27509739286784535
},
"riskLevels": {
"overall": 0,
"testPositivityRatio": 4,
"caseDensity": 0,
"contactTracerCapacityRatio": 4,
"infectionRate": 3,
"icuHeadroomRatio": 4,
"icuCapacityRatio": 4
},
"actuals": {
"cases": 363,
"deaths": 2,
"positiveTests": null,
"negativeTests": null,
"contactTracers": null,
"hospitalBeds": {
"capacity": null,
"currentUsageTotal": null,
"currentUsageCovid": null,
"typicalUsageRate": null
},
"icuBeds": {
"capacity": null,
"currentUsageTotal": null,
"currentUsageCovid": null,
"typicalUsageRate": null
},
"newCases": 0,
"newDeaths": 0,
"vaccinesDistributed": null,
"vaccinationsInitiated": null,
"vaccinationsCompleted": 918,
"vaccinesAdministered": null,
"vaccinesAdministeredDemographics": null,
"vaccinationsInitiatedDemographics": null
},
"annotations": {
"cases": {
"sources": [
{
"type": "NYTimes",
"url": "https://github.com/nytimes/covid-19-data",
"name": "The New York Times"
}
],
"anomalies": []
},
"deaths": {
"sources": [
{
"type": "NYTimes",
"url": "https://github.com/nytimes/covid-19-data",
"name": "The New York Times"
}
],
"anomalies": []
},
"positiveTests": null,
"negativeTests": null,
"contactTracers": null,
"hospitalBeds": null,
"icuBeds": null,
"newCases": null,
"newDeaths": null,
"vaccinesDistributed": null,
"vaccinationsInitiated": null,
"vaccinationsCompleted": {
"sources": [
{
"type": "other",
"url": "https://covid.cdc.gov/covid-data-tracker/#county-view",
"name": "Centers for Disease Control and Prevention"
}
],
"anomalies": []
},
"vaccinesAdministered": null,
"testPositivityRatio": null,
"caseDensity": {
"sources": [
{
"type": "NYTimes",
"url": "https://github.com/nytimes/covid-19-data",
"name": "The New York Times"
}
],
"anomalies": []
},
"contactTracerCapacityRatio": null,
"infectionRate": {
"sources": [
{
"type": "NYTimes",
"url": "https://github.com/nytimes/covid-19-data",
"name": "The New York Times"
}
],
"anomalies": []
},
"infectionRateCI90": {
"sources": [
{
"type": "NYTimes",
"url": "https://github.com/nytimes/covid-19-data",
"name": "The New York Times"
}
],
"anomalies": []
},
"icuHeadroomRatio": null,
"icuCapacityRatio": null,
"vaccinationsInitiatedRatio": null,
"vaccinationsCompletedRatio": null
},
"lastUpdatedDate": "2021-04-26",
"url": "https://covidactnow.org/us/alaska-ak/county/aleutians_east_borough"
}
]
const enteredCountryName = "US";
//Getting the required country name from the array of objects using filter method
const countryArray = response.filter(item => item.country === enteredCountryName)
const noOfDeaths = countryArray[0].actuals.deaths;
const noOfCases = countryArray[0].actuals.cases;
console.log({noOfDeaths, noOfCases})
If you are only interested in a specific county, there is an endpoint for this in the API. Just query this, then there is no need to filter the fetched data further:
https://api.covidactnow.org/v2/county/{fips}.json?apiKey=YOUR_KEY_HERE

How to fetch multiple values from a nested JSON like output

I am looking forward a way to list the value from a nested variable (which has dict and list values) ie register which is response_find and I have that in mostly json format and most of the values inside the json are nested within [] list like construct.
It works somehow if I get individual values from it like below:
var=response_find['json']['results'][0]['content_facet_attributes']
or
var=response_find['json']['results'][0]['certname']
But did not work when I did below:
var=response_find['json']['results'][0]['content_view_id']
Below are few values which I'm looking forward to fetch from this nested output:
"architecture_name": "x86_64",
"name": "satcap.rest.example.com",
"url": "https://satcap.rest.example.com:9090"
"content_source_name": "satcap.rest.example.com",
"name": "ccv-azure-infra-rhel7"
"name": "Prod"
"id": 33485,
"ip": "192.168.88.88",
"name": "invwharn108.test.exampl.com",
"registered_through": "satcap.rest.example.com"
Nested Json output:
{
"response_find": {
"apipie_checksum": "7533ab625c45a3819647f4fb4c9394c2832c0180",
"cookies": {
"_session_id": "25872833d9e2723073797fbd8cfa2d63"
},
"cookies_string": "_session_id=25872833d9e2723073797fbd8cfa2d63",
"foreman_version": "1.24.1.21",
"json": {
"page": 1,
"per_page": 20,
"results": [
{
"architecture_id": 1,
"architecture_name": "x86_64",
"build": false,
"capabilities": [
"build"
],
"certname": "invwharn108.test.exampl.com",
"comment": null,
"content_facet_attributes": {
"applicable_module_stream_count": 0,
"applicable_package_count": 0,
"content_source": {
"id": 17,
"name": "satcap.rest.example.com",
"url": "https://satcap.rest.example.com:9090"
},
"content_source_id": 17,
"content_source_name": "satcap.rest.example.com",
"content_view": {
"id": 67,
"name": "ccv-azure-infra-rhel7"
},
"content_view_id": 67,
"content_view_name": "ccv-azure-infra-rhel7",
"errata_counts": {
"bugfix": 0,
"enhancement": 0,
"security": 0,
"total": 0
},
"id": 32255,
"kickstart_repository": {
"id": 5772,
"name": "Red Hat Enterprise Linux 7 Server Kickstart x86_64 7.8"
},
"kickstart_repository_id": 5772,
"kickstart_repository_name": "5772",
"lifecycle_environment": {
"id": 5,
"name": "Prod"
},
"lifecycle_environment_id": 5,
"lifecycle_environment_name": "Prod",
"upgradable_module_stream_count": 0,
"upgradable_package_count": 0,
"uuid": "dab2d66b-1a73-490a-aa9d-3f036658980a"
},
"created_at": "2020-12-23 13:19:35 UTC",
"disk": null,
"domain_id": 25,
"domain_name": "test.example-aws.example.com",
"enabled": true,
"environment_id": null,
"environment_name": null,
"errata_status": 1,
"errata_status_label": "Could not calculate errata status, ensure host is registered and the katello-host-tools package is installed",
"global_status": 1,
"global_status_label": "Warning",
"hostgroup_id": 982,
"hostgroup_name": "infra",
"hostgroup_title": "NXDI-hg-aws/west-europe/infra",
"id": 33485,
"image_file": "",
"image_id": null,
"image_name": null,
"installed_at": null,
"ip": "192.168.88.88",
"ip6": null,
"last_compile": "2020-12-23 13:19:38 UTC",
"last_report": null,
"location_id": 37,
"location_name": "west-europe",
"mac": "02:78:43:60:ee:fb",
"managed": false,
"medium_id": null,
"medium_name": null,
"model_id": 25,
"model_name": "HVM domU",
"name": "invwharn108.test.exampl.com",
"openscap_proxy": null,
"openscap_proxy_id": null,
"openscap_proxy_name": null,
"operatingsystem_id": 21,
"operatingsystem_name": "RedHat 7.8",
"organization_id": 3,
"pxe_loader": "PXELinux BIOS",
"subnet_id": 65,
"subnet_name": "aws-west-europe-infra",
"subscription_facet_attributes": {
"autoheal": true,
"hypervisor": false,
"id": 33593,
"last_checkin": "2020-12-23 13:19:42 UTC",
"purpose_addons": [],
"purpose_role": "",
"purpose_usage": "",
"registered_at": "2020-12-23 13:19:35 UTC",
"registered_through": "satcap.rest.example.com",
},
"subscription_global_status": 1,
"subscription_status": 1,
"subscription_status_label": "Partially entitled",
}
],
"search": "name=invwharn108.test.exampl.com",
"sort": {
"by": null,
"order": null
},
"subtotal": 1,
"total": 13121
},
"msg": "OK (unknown bytes)",
"x_request_id": "e02dd9b3-b2f8-4c39-8bf5-1ce1897d9548",
}
}
My Play:
---
- hosts: localhost
tasks:
- include_vars: vaults/aws_secrets.yml
no_log: true
- include_vars: requirements.yml
no_log: true
- name: Find the ID of Cloud VM in Satellite
uri:
url: "https://{{ satserver }}/api/v2/hosts?search=name={{ aws_instance_name }}"
method: GET
user: "{{ aws_satuser }}"
password: "{{ aws_satpw }}"
force_basic_auth: yes
validate_certs: no
register: response_find
delegate_to: localhost
changed_when: false
- debug:
var=response_find['json']['results'][0]['content_facet_attributes']
#var=response_find.json.results.0.organization_name
#var=response_find['json']['results'][0]['certname']
Result:
"content_facet_attributes": {
"applicable_module_stream_count": 0,
"applicable_package_count": 0,
"content_source": {
"id": 17,
"name": "satcap.rest.example.com",
"url": "https://satcap.rest.example.com:9090"
},
"content_source_id": 17,
"content_source_name": "satcap.rest.example.com",
"content_view": {
"id": 67,
"name": "ccv-azure-infra-rhel7"
},
"content_view_id": 67,
"content_view_name": "ccv-azure-infra-rhel7",
"errata_counts": {
"bugfix": 0,
"enhancement": 0,
"security": 0,
"total": 0
},
"id": 32255,
"kickstart_repository": {
"id": 5772,
"name": "Red Hat Enterprise Linux 7 Server Kickstart x86_64 7.8"
},
"kickstart_repository_id": 5772,
"kickstart_repository_name": "5772",
"lifecycle_environment": {
"id": 5,
"name": "Prod"
},
"lifecycle_environment_id": 5,
"lifecycle_environment_name": "Prod",
"upgradable_module_stream_count": 0,
"upgradable_package_count": 0,
"uuid": "dab2d66b-1a73-490a-aa9d-3f036658980a"
},
If you want to do a dictionary out of those data you listed, you could use the filter json_query, which is using JMESPath to parse and process JSON.
In order to extract a dictionary looking like:
{
"architecture_name": "x86_64",
"content_source_name": "satcap.rest.example.com",
"content_source_url": "https://satcap.rest.example.com:9090",
"content_view_name": "ccv-azure-infra-rhel7",
"egistered_through": "satcap.rest.example.com",
"id": 33485,
"ip": "192.168.88.88",
"lifecycle_environment_name": "Prod",
"name": "invwharn108.test.exampl.com"
}
You could use JMESPath to filter multiselect hashes.
Here is a JMESPath query that would give this result:
json.results[*].{
"architecture_name": architecture_name,
"content_source_name": content_facet_attributes.content_source.name,
"content_source_url": content_facet_attributes.content_source.url,
"content_view_name": content_facet_attributes.content_view.name,
"lifecycle_environment_name": content_facet_attributes.lifecycle_environment.name,
"id": id,
"ip": ip,
"name": name,
"egistered_through": subscription_facet_attributes.registered_through
}
Here is an example playbook using this:
- hosts: localhost
gather_facts: no
tasks:
- debug:
msg: >-
{{
(
response_find | json_query('
json.results[*].{
"architecture_name": architecture_name,
"content_source_name": content_facet_attributes.content_source.name,
"content_source_url": content_facet_attributes.content_source.url,
"content_view_name": content_facet_attributes.content_view.name,
"lifecycle_environment_name": content_facet_attributes.lifecycle_environment.name,
"id": id,
"ip": ip,
"name": name,
"egistered_through": subscription_facet_attributes.registered_through
}
')
).0
}}
vars:
{
"response_find": {
"apipie_checksum": "7533ab625c45a3819647f4fb4c9394c2832c0180",
"cookies": {
"_session_id": "25872833d9e2723073797fbd8cfa2d63"
},
"cookies_string": "_session_id=25872833d9e2723073797fbd8cfa2d63",
"foreman_version": "1.24.1.21",
"json": {
"page": 1,
"per_page": 20,
"results": [{
"architecture_id": 1,
"architecture_name": "x86_64",
"build": false,
"capabilities": [
"build"
],
"certname": "invwharn108.test.exampl.com",
"comment": null,
"content_facet_attributes": {
"applicable_module_stream_count": 0,
"applicable_package_count": 0,
"content_source": {
"id": 17,
"name": "satcap.rest.example.com",
"url": "https://satcap.rest.example.com:9090"
},
"content_source_id": 17,
"content_source_name": "satcap.rest.example.com",
"content_view": {
"id": 67,
"name": "ccv-azure-infra-rhel7"
},
"content_view_id": 67,
"content_view_name": "ccv-azure-infra-rhel7",
"errata_counts": {
"bugfix": 0,
"enhancement": 0,
"security": 0,
"total": 0
},
"id": 32255,
"kickstart_repository": {
"id": 5772,
"name": "Red Hat Enterprise Linux 7 Server Kickstart x86_64 7.8"
},
"kickstart_repository_id": 5772,
"kickstart_repository_name": "5772",
"lifecycle_environment": {
"id": 5,
"name": "Prod"
},
"lifecycle_environment_id": 5,
"lifecycle_environment_name": "Prod",
"upgradable_module_stream_count": 0,
"upgradable_package_count": 0,
"uuid": "dab2d66b-1a73-490a-aa9d-3f036658980a"
},
"created_at": "2020-12-23 13:19:35 UTC",
"disk": null,
"domain_id": 25,
"domain_name": "test.example-aws.example.com",
"enabled": true,
"environment_id": null,
"environment_name": null,
"errata_status": 1,
"errata_status_label": "Could not calculate errata status, ensure host is registered and the katello-host-tools package is installed",
"global_status": 1,
"global_status_label": "Warning",
"hostgroup_id": 982,
"hostgroup_name": "infra",
"hostgroup_title": "NXDI-hg-aws/west-europe/infra",
"id": 33485,
"image_file": "",
"image_id": null,
"image_name": null,
"installed_at": null,
"ip": "192.168.88.88",
"ip6": null,
"last_compile": "2020-12-23 13:19:38 UTC",
"last_report": null,
"location_id": 37,
"location_name": "west-europe",
"mac": "02:78:43:60:ee:fb",
"managed": false,
"medium_id": null,
"medium_name": null,
"model_id": 25,
"model_name": "HVM domU",
"name": "invwharn108.test.exampl.com",
"openscap_proxy": null,
"openscap_proxy_id": null,
"openscap_proxy_name": null,
"operatingsystem_id": 21,
"operatingsystem_name": "RedHat 7.8",
"organization_id": 3,
"pxe_loader": "PXELinux BIOS",
"subnet_id": 65,
"subnet_name": "aws-west-europe-infra",
"subscription_facet_attributes": {
"autoheal": true,
"hypervisor": false,
"id": 33593,
"last_checkin": "2020-12-23 13:19:42 UTC",
"purpose_addons": [],
"purpose_role": "",
"purpose_usage": "",
"registered_at": "2020-12-23 13:19:35 UTC",
"registered_through": "satcap.rest.example.com"
},
"subscription_global_status": 1,
"subscription_status": 1,
"subscription_status_label": "Partially entitled"
}],
"search": "name=invwharn108.test.exampl.com",
"sort": {
"by": null,
"order": null
},
"subtotal": 1,
"total": 13121
},
"msg": "OK (unknown bytes)",
"x_request_id": "e02dd9b3-b2f8-4c39-8bf5-1ce1897d9548"
}
}
Which gives the recap:
PLAY [localhost] *************************************************************************************************
TASK [debug] *****************************************************************************************************
ok: [localhost] => {
"msg": {
"architecture_name": "x86_64",
"content_source_name": "satcap.rest.example.com",
"content_source_url": "https://satcap.rest.example.com:9090",
"content_view_name": "ccv-azure-infra-rhel7",
"egistered_through": "satcap.rest.example.com",
"id": 33485,
"ip": "192.168.88.88",
"lifecycle_environment_name": "Prod",
"name": "invwharn108.test.exampl.com"
}
}
PLAY RECAP *******************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Google Apps Script receive webhooks from Stripe, failed to extract part of the received event information

Following up on another questions (the reply works!):
How to use Google Apps Script to get POST request from Stripe webhooks
I have revised my code as follow:
function doPost(e) {
var jsonString = e.postData.contents;
var event = JSON.parse(jsonString)
var ss = SpreadsheetApp.openById("xxx");
var sheet = ss.getSheetByName("xxx");
var timeStamp = new Date();
var time = Utilities.formatDate(timeStamp, "GMT+08:00", "MM/dd/yy, h:mm a");
var lastRow = sheet.getLastRow();
//Insert the data into the sheet
sheet.getRange(lastRow + 1, 1).setValue(time);
sheet.getRange(lastRow + 1, 2).setValue(event["data"]["object"]["id"]);
sheet.getRange(lastRow + 1, 3).setValue(event["data"]["object"]["amount_paid"]);
sheet.getRange(lastRow + 1, 4).setValue(event["data"]["object"]["customer_email"]);
sheet.getRange(lastRow + 1, 5).setValue(event["data"]["object"]["lines"]["data"]["description"]);
return HtmlService.createHtmlOutput(200);
}
For the last .setValue one, I can not get the string "description", the request information is as follow:
{
"created": 1326853478,
"livemode": false,
"id": "evt_00000000000000",
"type": "invoice.payment_succeeded",
"object": "event",
"request": null,
"pending_webhooks": 1,
"api_version": null,
"data": {
"object": {
"id": "in_00000000000000",
"object": "invoice",
"account_country": "HK",
"account_name": "xxx",
"amount_due": 400,
"amount_paid": 400,
"amount_remaining": 0,
"application_fee_amount": null,
"attempt_count": 1,
"attempted": true,
"auto_advance": false,
"billing_reason": "subscription_create",
"charge": "_00000000000000",
"collection_method": "charge_automatically",
"created": 1570506796,
"currency": "hkd",
"custom_fields": null,
"customer": "cus_00000000000000",
"customer_address": null,
"customer_email": "xxx",
"customer_name": null,
"customer_phone": null,
"customer_shipping": null,
"customer_tax_exempt": "none",
"customer_tax_ids": [
],
"default_payment_method": null,
"default_source": null,
"default_tax_rates": [
],
"description": null,
"discount": null,
"due_date": null,
"ending_balance": 0,
"footer": null,
"hosted_invoice_url": "xxx",
"invoice_pdf": "xxx",
"lines": {
"data": [
{
"id": "il_00000000000000",
"object": "line_item",
"amount": 0,
"currency": "hkd",
"description": "xxx",
"discountable": true,
"livemode": false,
"metadata": {
"code": "xxx",
"user_id": "xxx",
"hashId": "xxx"
},
"period": {
"end": 1607183999,
"start": 1591607019
},
"plan": {
"id": "plan_00000000000000",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 10000,
"amount_decimal": "10000",
"billing_scheme": "per_unit",
"created": 1591603592,
"currency": "hkd",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {
},
"nickname": null,
"product": "prod_00000000000000",
"tiers": null,
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
},
"price": {
"id": "plan_00000000000000",
"object": "price",
"active": true,
"billing_scheme": "per_unit",
"created": 1591603592,
"currency": "hkd",
"livemode": false,
"lookup_key": null,
"metadata": {
},
"nickname": null,
"product": "prod_00000000000000",
"recurring": {
"aggregate_usage": null,
"interval": "month",
"interval_count": 1,
"usage_type": "licensed"
},
"tiers_mode": null,
"transform_quantity": null,
"type": "recurring",
"unit_amount": 10000,
"unit_amount_decimal": "10000"
},
"proration": false,
"quantity": 1,
"subscription": "sub_00000000000000",
"subscription_item": "si_00000000000000",
"tax_amounts": [
],
"tax_rates": [
],
"type": "subscription"
}
],
"has_more": false,
"object": "list",
"url": "xxx"
},
"livemode": false,
"metadata": {
},
"next_payment_attempt": null,
"number": "xxx",
"paid": true,
"payment_intent": "pi_00000000000000",
"period_end": 1570506796,
"period_start": 1570506796,
"post_payment_credit_notes_amount": 0,
"pre_payment_credit_notes_amount": 0,
"receipt_number": null,
"starting_balance": 0,
"statement_descriptor": null,
"status": "paid",
"status_transitions": {
"finalized_at": xxx,
"marked_uncollectible_at": null,
"paid_at": xxx,
"voided_at": null
},
"subscription": "sub_00000000000000",
"subtotal": 400,
"tax": null,
"tax_percent": null,
"total": 400,
"total_tax_amounts": [
],
"transfer_data": null,
"webhooks_delivered_at": 1570506798,
"closed": true
}
}
}

How to extract multiple correlating variables from a JSon

I have to extract multiple correlating variables from a response (which is json) in JMeter. Part of the response is listed below:
[
{
"data": {
"id": "efaa6876-7a8d-4723-9d85-1ed99e822f06",
"type": "courses",
"attributes": {
"created-at": "2019-02-07T16:38:50.735Z",
"contents-count": 267,
"units": [
{
"id": "31b5fcb1-24ee-441e-a0ee-ca859fc9a89d",
"position": null,
"progress": 0,
"completed": false,
"show_name": false,
"node_id": "1",
"children": [
{
"id": "b8ed75a3-0390-4273-82c3-03ee6eba729c",
"position": null,
"image": null,
"progress": 0,
"completed": false,
"show_name": true,
"node_id": "2",
"children": [],
"contents": [
{
"id": "fa1bdc2f-4330-425c-9c10-3734d07125aa",
"link": {
"url": "#",
"target": "_blank",
"class": "learning-object-link",
"data": {
"id": "fa1bdc2f-4330-425c-9c10-3734d07125aa",
"user-role": "teacher",
"open-method-tablet": "newtab",
"open-method-desktop": "modal",
"content-open-method": null,
"modal-size-method": "fully_responsive",
"fixed-width": null,
"fixed-height": null,
"aspect-ratio": null
}
},
"is_work": false,
"is_fun": false,
"completed": false,
"total_activities": 2,
"completed_activities": 0,
"progress": 0,
"updated_at": false,
"attempts": 0,
"duration": null
},
{
"id": "ceceabfd-5151-4656-af5d-3392c5a4c04c",
"link": {
"url": "#",
"target": "_blank",
"class": "learning-object-link",
"data": {
"id": "ceceabfd-5151-4656-af5d-3392c5a4c04c",
"user-role": "teacher",
"open-method-tablet": "newtab",
"open-method-desktop": "modal",
"content-open-method": null,
"modal-size-method": "fully_responsive",
"fixed-width": null,
"fixed-height": null,
"aspect-ratio": null
}
},
"is_work": false,
"is_fun": false,
"completed": false,
"total_activities": 2,
"completed_activities": 0,
"progress": 0,
"updated_at": false,
"attempts": 0,
"duration": null
}
]
},
{
"id": "60639cbd-f872-492d-b8e9-db83f8789fcf",
"position": null,
"image": null,
"progress": 0,
"completed": false,
"show_name": true,
"node_id": "3",
"children": [],
"contents": [
{
"id": "1825f834-7099-4bb4-b7a2-fc634faffc86",
"link": {
"url": "#",
"target": "_blank",
"class": "learning-object-link",
"data": {
"id": "1825f834-7099-4bb4-b7a2-fc634faffc86",
"user-role": "teacher",
"open-method-tablet": "newtab",
"open-method-desktop": "modal",
"content-open-method": null,
"modal-size-method": "fully_responsive",
"fixed-width": null,
"fixed-height": null,
"aspect-ratio": null
}
},
To proceed with the next request, I have to extract unit id (e.g. 31b5fcb1-24ee-441e-a0ee-ca859fc9a89d), children id (e.g. b8ed75a3-0390-4273-82c3-03ee6eba729c) and contents id (e.g. fa1bdc2f-4330-425c-9c10-3734d07125aa). There are several units, each unit has several children and each children has several contents. Each content id matches just one children id and each children id matches just one unit id. Ids have to be selected on a random basis.
I've tried to extract all ids from the response and use them randomly, but it doesn't work this way.
To extract only Unit Ids, you can use following JSON Path Expressions:
$..data.attributes.units[?(#.id)].id
Random Value for Unit Id also can be extracted using JMeter JSON Extractor:

Network IP addresses with jq bash command from docker inspect

I want to process docker inspect <container1> <container2> out to retrieve via jq command exposed ports and IPAddresses assigned to defined networks. So far I've got jq '{(.[].Name): getpath(path(.[].NetworkSettings.Networks)) | .[].IPAddress}' which is clearly far from enough.
p.s. I know its easy to write a script that would give such output but I'm curious how to do that using jq
Expected output
{
# .[].Name
"/prometheus_prometheus_1": [
[
# .[].Config.ExposedPorts
"9090/tcp"
],
{
# key = .[].NetworkSettings.Networks.<index>
# value = .[].NetworkSettings.Networks[].IPAddress
"prometheus_internal": "172.21.0.4",
"system-information": "172.28.0.2"
}
]
}
Input:
[
{
"Id": "c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa",
"Created": "2018-06-12T05:33:19.811448302Z",
"Path": "/bin/prometheus",
"Args": [
"--config.file=/etc/prometheus/prometheus.yml",
"--storage.tsdb.path=/prometheus",
"--web.console.libraries=/usr/share/prometheus/console_libraries",
"--web.console.templates=/usr/share/prometheus/consoles"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 13217,
"ExitCode": 0,
"Error": "",
"StartedAt": "2018-06-12T05:33:20.264845701Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:44a4c1c270dcb5e8caf51e3205fa23343cc903f3823eab53ae204f304d16f62a",
"ResolvConfPath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/hostname",
"HostsPath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/hosts",
"LogPath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa-json.log",
"Name": "/prometheus_prometheus_1",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": [
"prometheus_prometheus-data:/prometheus:rw",
"/home/sebastian/projects/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:rw"
],
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {}
},
"NetworkMode": "prometheus_internal",
"PortBindings": {},
"RestartPolicy": {
"Name": "always",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": [],
"CapAdd": null,
"CapDrop": null,
"Dns": null,
"DnsOptions": null,
"DnsSearch": null,
"ExtraHosts": null,
"GroupAdd": null,
"IpcMode": "shareable",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 67108864,
"Runtime": "runc",
"ConsoleSize": [
0,
0
],
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": null,
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": null,
"DeviceCgroupRules": null,
"DiskQuota": 0,
"KernelMemory": 0,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": null,
"OomKillDisable": false,
"PidsLimit": 0,
"Ulimits": null,
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0
},
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac-init/diff:/var/lib/docker/overlay2/03c66042305488fea2fe693246e90374743fbb7836ab31e4ee5cdbfbb1c97785/diff:/var/lib/docker/overlay2/80821a00b79334493729e671dfb66cc878aec19fe2d0dfbaf4cde187522b06e8/diff:/var/lib/docker/overlay2/f5071cce5513fb3c465ad883297157271ef48c6f59cd88768068224d850c6903/diff:/var/lib/docker/overlay2/c9a0cc617abb45fbd4572abb41c7281c96bc9d59c109270c7f1ec7a99f5b055b/diff:/var/lib/docker/overlay2/5b425f8a440139a8fdcdd7f7fee8189565e9e00304e96f4cfee86ff6b861e068/diff:/var/lib/docker/overlay2/e85740d997591d2f60bfa61ea0c82a58636bccaaba970e55f12cf0ff24565c70/diff:/var/lib/docker/overlay2/e9c362d971c460b02111122b241888392d77c5b8545ed520c3d74660b16db9b2/diff:/var/lib/docker/overlay2/5001184fc8ddd25204626f419c1530b970cb37f936a196fb1173f2774310085e/diff:/var/lib/docker/overlay2/ed2e676f09a4583f2194e752083a7c95be80131f055891dc39f9fed5560f5a73/diff",
"MergedDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac/merged",
"UpperDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac/diff",
"WorkDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac/work"
},
"Name": "overlay2"
},
"Mounts": [
{
"Type": "volume",
"Name": "prometheus_prometheus-data",
"Source": "/var/lib/docker/volumes/prometheus_prometheus-data/_data",
"Destination": "/prometheus",
"Driver": "local",
"Mode": "rw",
"RW": true,
"Propagation": ""
},
{
"Type": "bind",
"Source": "/home/sebastian/projects/prometheus/prometheus.yml",
"Destination": "/etc/prometheus/prometheus.yml",
"Mode": "rw",
"RW": true,
"Propagation": "rprivate"
}
],
"Config": {
"Hostname": "c2f86bce6844",
"Domainname": "",
"User": "nobody",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"9090/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"--config.file=/etc/prometheus/prometheus.yml",
"--storage.tsdb.path=/prometheus",
"--web.console.libraries=/usr/share/prometheus/console_libraries",
"--web.console.templates=/usr/share/prometheus/consoles"
],
"Image": "prom/prometheus:v2.3.0",
"Volumes": {
"/etc/prometheus/prometheus.yml": {},
"/prometheus": {}
},
"WorkingDir": "/prometheus",
"Entrypoint": [
"/bin/prometheus"
],
"OnBuild": null,
"Labels": {
"com.docker.compose.config-hash": "b8ff39fd239739ae66051752c1b49b0119862b8f21678fb42400c907d25b1c57",
"com.docker.compose.container-number": "1",
"com.docker.compose.oneoff": "False",
"com.docker.compose.project": "prometheus",
"com.docker.compose.service": "prometheus",
"com.docker.compose.version": "1.16.1",
"maintainer": "The Prometheus Authors <prometheus-developers#googlegroups.com>"
}
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "7be77954d0e6990f565a8526b157236140238cabf0954629598ce3bb9aaae885",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"9090/tcp": null
},
"SandboxKey": "/var/run/docker/netns/7be77954d0e6",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": "",
"Networks": {
"prometheus_internal": {
"IPAMConfig": null,
"Links": null,
"Aliases": [
"prometheus",
"c2f86bce6844"
],
"NetworkID": "145c59986c16003f9a3a30e6b671c34b56225d90243fba88fc295c49b4dcfff6",
"EndpointID": "8e3ac8bd4719ea85358c20a8141c37377dd327265916d41ee5d1db6b7496898c",
"Gateway": "172.21.0.1",
"IPAddress": "172.21.0.4",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:15:00:04",
"DriverOpts": null
},
"system-information": {
"IPAMConfig": null,
"Links": null,
"Aliases": [
"prometheus",
"c2f86bce6844"
],
"NetworkID": "f6e67721cb73da7e8d4eacdb709de240014af9af35e66216e6186300c72de330",
"EndpointID": "2c31369f8175f2b38a5bc966a8306c8f0f11ac4c264e6ce735d00c87b8a6f44f",
"Gateway": "172.28.0.1",
"IPAddress": "172.28.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:1c:00:02",
"DriverOpts": null
}
}
}
}
]
jq solution:
jq '.[] | {(.Name) : [(.Config.ExposedPorts | keys),
(.NetworkSettings.Networks | to_entries
| map({(.key): .value.IPAddress}) | add)
]
}' input
The output:
{
"/prometheus_prometheus_1": [
[
"9090/tcp"
],
{
"prometheus_internal": "172.21.0.4",
"system-information": "172.28.0.2"
}
]
}