How to remove array present in Json in jmeter - jmeter

I have a json and I have to remove whole filter block from that ,How can i remove that?I tried below in JSR223PostProcessor but it is not working
var response = prev.getResponseDataAsString();
var responseWithoutIds = response.replaceAll("\"filter\"[ ]*:[^,}\\]]*[,]?", "");
{
"templateId": "1e5eef7d-9581-40a1-98ed-774dcf68ce11",
"ownerId": "241e992f-a1c7-430a-be9f-347337643697",
"orgId": "4c41a6d7-dfbf-485b-84b6-3a3991546d9c",
"createdDate": "2018-12-24T10:51:57.336Z",
"shareWithOrg": false,
"templateName": "custom template",
"templateDesc": null,
"system": false,
"optionIds": [
"9c9b93c9-4ada-4489-9129-604cf1fa35be",
"65285021-9c2c-4787-b810-390c50f48f9f",
"222c832d-8db6-4ca1-88ef-150b6a388d87",
"be22ba29-144b-4971-99de-0d4258220558",
"b7ab883b-fe51-4e02-bdb1-0d7321d30ac3",
"510660fa-d255-45e2-b6b8-c1c09c9009d6",
"51f78f08-b655-4a82-b0c5-61365881fb0a",
"ac1d4b39-f41c-4b69-bdc4-b76fd1d2b9af",
"2de3591e-c9eb-48bd-a9bf-acfcee695ac8",
"c9e2a1f1-f786-4e9a-9d11-525a5aa01345",
"441a0627-9983-4edc-95ce-a5b8e79f7f1d",
"087a1ac8-e7c1-4cee-ae31-4f0aaccba8c9",
"dba760fb-9e97-4dcb-b1ab-4a2795e59ee6",
"53bc5244-b33e-4732-8bf0-cd051e017089",
"2bf04285-fe19-4534-8467-44c08661da60",
"020eb946-6ba0-4519-b6f9-23ffafd949d0",
"ced89c82-5ba1-4fe6-bc83-5bddff820c85",
"18ea7006-2e29-4a3f-a28f-59a1323a4bd0",
"c7efa0d1-094c-4626-90aa-80e1343bbdef",
"6504605f-3a41-4406-9f0e-150365c8ee35",
"3c28c622-83b1-4b46-ac16-3c5cbff80999",
"6a227b18-519f-49c4-8c59-7fe0eaf73fea",
"f9127d4e-c27e-48fa-8286-42a045d8fc40",
"bb695a06-50fe-4419-924f-7fee96530b63",
"731393bc-92e0-4ddb-8113-a7b3942527c5",
"a355ee2d-c654-4406-9027-8e801cb1a4a9"
],
"optionGroupIds": [
"09f1302b-6ad0-486b-8f8c-e65ae14f5831",
"2041206d-cc87-4173-912c-fee52cefcf2b",
"6fc154fb-8313-488c-a2cb-e1a5b88b3028",
"cc0767f2-3e7f-42f1-b9c7-9f76991a6fcf",
"4cd75ade-db20-43fe-8b15-7effa961b4b5",
"6af8ddba-8a7c-4ff7-8043-6358b6e6a31b"
],
"filter": [
{
"optionId": "222c832d-8db6-4ca1-88ef-150b6a388d87",
"selectedValues": [
"all"
],
"selectedComplexValues": null,
"contextualFilterId": null,
"operator": "pastDays",
"filterType": "date"
}
],
"sortDirection": "desc",
"sortedOptionId": "222c832d-8db6-4ca1-88ef-150b6a388d87",
"templateCategory": "patients"
}

Using regular expressions is not the best way to proceed. Also consider switching to Groovy language, it provides JsonSlurper and JsonBuilder classes which way more reliable.
Example code:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
response.remove('filter')
def responseWithoutIds = new groovy.json.JsonBuilder(response).toPrettyString()
log.info(responseWithoutIds)
References:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Use below code in JSR223PostProcessor :
var body = prev.getResponseDataAsString();
var parsed = JSON.parse(body);
delete parsed.filter[0];
delete parsed.filter;
vars.put('value', JSON.stringify(parsed));

Related

Jmeter - How to get nested object in json with multiple object

I have this json:
{
"deviceId": "deviceCustom",
"moduleId": "custom",
"properties": {
"desired": {
"settings": {
"ef78c18c-2291-4d15-ae87-d89abb9b1fef": {
"name": "elements",
"version": "1.0.0",
"category": "A1"
},
"f4b04c94-4643-4b13-b10c-9a00fbf4ea27": {
"name": "tags",
"version": "2.0.0",
"category": "B1"
}
}
}
}
}
and I would like to get separately all the objects under "settings". E.g:
settings_1="f4b04c94-4643-4b13-b10c-9a00fbf4ea27":{"name":"tags","version":"2.0.0","category":"B1"}
settings_2="ef78c18c-2291-4d15-ae87-d89abb9b1fef":{"name":"elements","version":"1.0.0","category":"A1"}
settings_matchNr=2
In Jmeter I've configured a JSON Extractor with this JSON Path expression: $.properties.desired.settings but I got this result:
settings_1={"f4b04c94-4643-4b13-b10c-9a00fbf4ea27":{"name":"tags","version":"2.0.0","category":"B1"},"ef78c18c-2291-4d15-ae87-d89abb9b1fef":{"name":"elements","version":"1.0.0","category":"A1"}}
settings_matchNr=1
I've also tried to use JSR223 Post Processor with Slurper but no valid result.
Could you help me on that?
Thanks in advance.
Add JSR223 PostProcessor as a child of the request which returns the above JSON
Put the following code into "Script" area:
new groovy.json.JsonSlurper().parse(prev.getResponseData()).properties.desired.settings.entrySet().eachWithIndex { entry, index ->
def setting = [:]
setting.put(entry.getKey(), entry.getValue())
vars.put('setting_' + (index + 1), new groovy.json.JsonBuilder(setting).toPrettyString())
}
That's it, you will be able to refer the extracted JSON Objects as ${setting_1} and ${setting_2}
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Spring MVC Converter and Swagger doc: how to?

I use converters in my Spring MCV controllers. In this example, the String from the path variable is mapped into a UserId:
#GetMapping(path = "/user/{user-id}")
public User get(#Parameter(description = "User id", required = true, example = "3fa85f64-5717-4562-b3fc-2c963f66afa6")
#PathVariable("user-id")
UserId userId) {
return userService.get(userId)
}
It seems to annoy Swagger as the generated doc requires an object as parameter and not a plain string:
...
"/api/v1/user/{user-id}": {
"get": {
"operationId": "get",
"parameters": [
{
"name": "user-id",
"in": "path",
"schema": {
"$ref": "#/components/schemas/UserId"
},
}
],
...
with the UserId schema:
"UserId": {
"type": "object",
"properties": {
"value": {
"type": "string",
"format": "uuid"
}
}
}
And thus the Swagger UI cannot be used because either the parameter is considered as invalid when a single string is provided, either the data is actually invalid when the object format is used.
What is an option to fix that?
To achieve that, the schema parameter of the #Parameter annotation is the answer.
The above example becomes:
#Parameter(description = "User id",
required = true,
schema = #Schema(implementation = String.class), // this is new
example = "3fa85f64-5717-4562-b3fc-2c963f66afa6")

How to iterate through the contents of a Json object

On the JSR223 assertion in Jmeter, I need to validate only the inner part of the JSON returned.
I followed this thread to get an idea on the validation.
​How can I write JSON schema validation for JMeter run in TeamCity
Basically my Jmeter sampler returns the json as follows. On my schema, the validation should be for items, service and requestId. No validation should be performed for "payload".
{
"payload": [
{
"items": [
{
"code": "487482378",
"description": "Alpha Co",
"valid": true
},
{
"code": "92901128365",
"description": "Beta Co",
"valid": true
}
],
"service": "entities",
"requestId": "d190219"
}
]
}
This is my current code in the js223 sampler:
var schemaPath = '/path/entities-schema.json'
var rawSchema = new org.json.JSONObject(new org.json.JSONTokener(org.apache.commons.io.FileUtils.readFileToString(new java.io.File(schemaPath), 'UTF-8')))
var schema = org.everit.json.schema.loader.SchemaLoader.load(rawSchema)
schema.validate(new org.json.JSONObject(prev.getResponseDataAsString()))
You can remove the "unwanted" part of the response using JSR223 PostProcessor like:
def before = prev.getResponseDataAsString()
log.info('Before: ' + before)
def response = new groovy.json.JsonSlurper().parseText(before)
def after = new groovy.json.JsonBuilder(response.payload.items).toPrettyString()
log.info('After: ' + after)
prev.setResponseData(after, 'UTF-8')
Once done you can use your JSON Schema validation approach against the new content without elements you don't need.
References:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

I need to extract value from JSON response only if the key "has_products" = true . Is it possible to extract in Jmeter?

My Json Response is as below:
{
"id":2,
"parent_id":1,
"has_products":false,
"has_categories":true,
"image":"",
"image_thumbs":[ ],
"name":"Default Category",
"categories":[
{
"id":3,
"parent_id":2,
"has_products":false,
"has_categories":true,
"image":"https:\/\/storage.googleapis.com\/gcs-rezolve-commerce-engine-dev-media\/1%2F26%2Fcategory%2Fimages_7_.jpg?GoogleAccessId=rcedev#ferrous-layout-183111.iam.gserviceaccount.com&Expires=1515750870&Signature=BUVCdagE09Do%2B%2B6S9FXzmGUCJQP4QYHvoOuKOuLUQz9pJGwtwtkVF6h%2BuTzo5Jdqv%2F%2B4ACIw8WCWoT%2B8KQgNDpXA%2FCY2dkCDsfxb1VRXS0ff5dp4%2F2cq3WjE%2B8biudDXvhQvSWYx%2FyS%2FAYKkK%2FIXRqQ%2FlimDIYUR%2BRgdH6aEze4FNW5vCtGAHK%2BlscQ9GSFeG%2BN6KxMwFbjNpNNZT8KZ%2BLpdKbiHca%2Fk86TeYkmnvICdHpnaDqQJHGbofH%2BFPcbOWnjVCn9uD4gJQnfS4Y7a4OWdhG1q60Kr6KNpKmSOhOcD1P1NHFTn8SYI6GemGJPUXZ8Y3A40etORw1yfJC4M4Q%3D%3D",
"image_thumbs":[
],
"name":"Home Decors",
"categories":null
},
{
"id":4,
"parent_id":2,
"has_products":false,
"has_categories":true,
"image":"https:\/\/storage.googleapis.com\/gcs-rezolve-commerce-engine-dev-media\/1%2F26%2Fcategory%2F332034-jewelry.png?GoogleAccessId=rcedev#ferrous-layout-183111.iam.gserviceaccount.com&Expires=1515750870&Signature=OxdyQ6mYX5Shoz4pBf40MZr9I9PFdYUqD3Rihbn8EOpbj%2FekHSFiWGdUYZ1HeZmpB9mZ49qhKh3b0E25H%2FRPVvzv6MURzYOg4EfRa66KrjFAQVP5WbgC5dVzpKc2Nh8FWn4%2FgA70gQ1mE3Uh1KF62Tw2aFvlbughPM5ijC2j35xHTAYcnNhr2Pcx4%2B9%2BWVHecXCdvw%2Fy3CMrgmZGZFSfALNBsiSM8IKKtRXwqHqVRg9CwutbaVL5zDd0GbTdBhwZLlJxqAx9Z1RE4l78Rv3bA2BeLhk5OqX2ajU5YYEQC69tTm0Mq9jzNF7%2F9zhtwCsqDfiygmdMKs9D7vDqD0xD%2Fg%3D%3D",
"image_thumbs":[
"https:\/\/storage.googleapis.com\/gcs-rezolve-commerce-engine-dev-media\/1%2F26%2Fcategory%2F332034-jewelry_thumb_400x376.png?GoogleAccessId=rcedev#ferrous-layout-183111.iam.gserviceaccount.com&Expires=1515750870&Signature=bOX4Z8EZwHb80ZNWtJ%2BrTq5hkUMNkTMGrtjk%2BvEyJ9H0XSDUMsmZVgMjgZVprgc23oLBR2SCDGvLNJKkCij2GIX1X9HT7QCFt4uLgvFy%2FmATHDcI9AOL55P8ypv7GJHBeUU7jdJKl5o641Uvf2s22yTCZpJenIiJCzJyxGAN%2BRV%2FwyD0OXkcTYjgwpJ5zi6SK%2BOYY5EGfTqFQBEbuG9WUAvNgeY3fCFgWoRgrp2XuxM5meXlcT7WA%2FZzt6wougjimBQsdF03s04Kq3cR6jsiL6aZFjhQacToBtkLFF7xY30dQr%2FO0D3tgs57QJXdD45QPBX4dAhgV2fSo%2BDK4D1kwQ%3D%3D"
],
"name":"jewelry",
"categories":null
},
{
"id":10,
"parent_id":2,
"has_products":true,
"has_categories":false,
"image":"",
"image_thumbs":[
],
"name":"Ring Collection",
"categories":null
}
]
}
Can any one help me on this ?
Assuming that the value you want to extract is the id, then add a JSON Extractor with the below configurations:
Variable names : the name of the variable which will hold the value.
JSON Path expressions : $.categories[?(#.has_products == true)].id
Match Numbers : 1 // use -1 if you want to extract all id values which pass the condition.
Default values : NOT_FOUND
Reference:
advanced-usage-json-path-extractor-jmeter but use Core JMeter JSON Extractor instead of the plugin mentioned in blog

How to check whether Google User's image is default or uploaded?

How do I check whether user's profile picture is default or uploaded in Google?
Note: When you get user details from APIs.
All of default profile pictures have the following URL:
https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg
You can just compare string equality of profile picture with the given one.
people.get includes a isDefault value in the image object. E.g. if you try it for +Google you will get;
"image": {
"url": "https://lh4.googleusercontent.com/-v0soe-ievYE/AAAAAAAAAAI/AAAAAAACyas/yR1_yhwBcBA/photo.jpg?sz=50",
"isDefault": false
}
people.get no longer has isDefault as a property.
https://developers.google.com/+/web/api/rest/latest/people#resource
Updating this answer for 2020: it's now possible to get the user's profile picture by sending a request to the people.get API with photos as the personFields to request.
You'll get back an array of images, and whenever default: true is present, it means it's a default (not user-set) image:
Example (if you're using this with OAuth):
GET https://people.googleapis.com/v1/people/me
Sample response (with profile picture)
{
"resourceName": "people/117055959617985617271",
"etag": "%EgQBAzcuGgQBAgUHIgxHamp6MG9wZ3hOcz0=",
"photos": [
{
"metadata": {
"primary": true,
"source": {
"type": "PROFILE",
"id": "117055959617985617271"
}
},
"url": "https://lh3.googleusercontent.com/a-/AOh14Gg_-udXd3O6K1URTBTEK2rLa2DOh6G2dgmOHcOBOtE=s100"
},
{
"metadata": {
"source": {
"type": "CONTACT",
"id": "2"
}
},
"url": "https://lh3.googleusercontent.com/a/default-user=s100",
"default": true
}
]
}
Sample response (default only)
{
"resourceName": "people/113009277022343767972",
"etag": "%EgQBAzcuGgQBAgUHIgxxdHVTY3IxZVJIUT0=",
"photos": [
{
"metadata": {
"primary": true,
"source": {
"type": "PROFILE",
"id": "113009277022343767972"
}
},
"url": "https://lh6.googleusercontent.com/-6NS3awoYRXw/AAAAAAAAAAI/AAAAAAAAAAA/AMZuucnTo-mElIpcAEazDV9DAs1VyYDEIw/s100/photo.jpg",
"default": true
}
]
}
in ruby with devise and omniauth-google-oauth2
in your devise.rb
config.omniauth :google_oauth2 (Other options....), skip_image_info: false
then in your user.rb / other place:
def self.parse_auth_image(auth)
if auth.provider == "google_oauth2"
return nil if auth.dig("extra", "raw_info", "image", "isDefault")
end
auth.info.image
end
The best way to do this in FULL DETAIL:
require 'open-uri'
Default image:
default = "https://lh3.googleusercontent.com/-
XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg"
Image to check:
image_to_check = "https://lh3.googleusercontent.com/-
uh4wK1JDtCI/AAAAAAAAAAI/AAAAAAAAAAA/huieBSbV4zg/s64-
c/100695019739939096169.jpg"
Comparison check
blob_for_default_image = open(default).read
blob_for_image_to_check = open(image_to_check).read
Then you compare the 2 image blobs:
blob_for_default_image == blob_for_image_to_check
If you are using PHP, It's fairly simple, just use this code
$profile_img_end = explode("/", $userData['picture']); // Exploding the URL and Dividing it into several terms
if (end($profile_img_end) === "photo.jpg") { // Now Simply Check if last part of array is equal to "photo.jpg" which is common in all default images
$profile_img = null; // If it's default then set it equal to null
} else {
$profile_img = $userData['picture']; // Else get the Link of the Image
}
Alternative in JavaScript
var url = ""; // Image URL
var img_split = url.split("/"); // Split it Again from / (forward slash)
if (img_split[img_split.length - 1] === 'photo.jpg') { // Check if last array is equal to photo.jpg (By Default Image)
var image = null;
} else {
var image = url;
}
HOPE IT HELPS!

Resources