I'm working with an API that returns response in the following format:
"products": [
{
"name": "ABC"
"id": "ABCDEFG"
"Status":Open
}
{
"name": "XYZ"
"id": "LMNOPQ"
"Status":Open
} ]
The number of products varies and so does the number of IDs generated. I need to extract all id values which I'm doing using a JSON extractor and setting the match number to -1.
I need to pass these ID values in this request:
"products": [
{
"id": "id1"
}
{
"id": "id2"
} ]
If there are 5 IDs then the request needs to contain 5 id values.
I've tried using loops but I can't figure out how to add a { "id": } to the request body on every iteration of the loop. Is there any way to simulate this?
Instead of using JSON Extractor you could do everything with JSR223 PostProcessor and extract the IDs and build the next request body in one shot.
Example code:
def ids = new groovy.json.JsonSlurper().parse(prev.getResponseData()).products.collect { product -> product.id }
def payload = [:]
def products = []
ids.each { id ->
products.add([id: id])
}
payload.put('products', products)
vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())
You will be able to refer generated value as ${payload} where required.
More information:
Apache Groovy: Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?
Related
Can you please let me know efficient way to extract all ItemID from below Json response and store extracted values in a variable with coma separated.
Example: JsonResponse of a request.
[
{
"ItemID": "ITM40400002",
"deliveryId": "1",
},
{
"ItemID": "ITM40400003",
"deliveryId": "2",
},
{
"ItemID": "ITM40400002",
"deliveryId": "3",
}
]
Extracted Variable
Items = ITM40400002,ITM40400003,ITM40400002
Add JSON Extractor as a child of the request which returns the above JSON
Configure it as follows:
Names of created variables: anything meaningful, i.e. foo
JSON Path Expressions: $..ItemID
Match No: -1
Tick Compute concatenation var
That's it, the JSON Extractor will extract all the ItemID attributes values and store them into foo_ALL JMeter Variable
Demo:
More information: API Testing With JMeter and the JSON Extractor
I am trying to extract a jsonArray from response of request1 and use it in request2. I am using JSONextractor the steps in this question but I am getting the array as different variables instead of 1 jsonArray.
My JsonExtractor:
Output of debug sampler:
Request:
{
"items": [
{
"id": "asd"
},
{
"id": "def"
},
{
"id": "hij"
}]
}
I don't know what I'm doing wrong that is extracting values in different variables instead of 1 jsonArray.
You can generate a JSON request body from the JMeter Variables which are coming from the JSON Extractor using JSR223 PreProcessor
Add JSR223 PreProcessor as a child of the request which you want to parameterize
Put the following code into "Script" area:
def payload = [:]
def items = []
1.upto(vars.get('userIds_matchNr') as int, { index ->
items.add([id: vars.get('userIds_' + index)])
})
payload.put('items', items)
vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())
You should be able to put the ${payload} JMeter Variable reference into the request "Body Data" tab
Demo:
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
I am getting response from one API and need to prepare the payload from that response.
For example the response as like
{
"data": {
"total_count": 5,
"userIds": [1,2,3,4,5]
}
Need to make the payload from the response to other API like
{
"users": [
{
"user_id": 1,
"invite_amount": 100,
},
{
"user_id": 2,
"invite_amount": 100
},
{
"user_id": 3,
"invite_amount": 100
},
{
"user_id": 4,
"invite_amount": 100
},
{
"user_id": 5,
"invite_amount": 100
}
]
}
Above payload need to send to the another API
Add JSR223 PostProcessor as a child of the request which returns the above JSON
Put the following code into "Script" area:
def userIds = new groovy.json.JsonSlurper().parse(prev.getResponseData()).data.userIds
def payload = [:]
def users = []
userIds.each { userId ->
def user = [:]
user.put('user_id', userId)
user.put('invite_amount', 100)
users.add(user)
}
payload.put('users', users)
vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())
That's it, you will be able to refer the generated payload value as ${payload} where required
More information:
JsonSlurper and JsonBuilder
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
Have a look at this link
Basically you need to use JMeter JSON Extractor
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
My Response is:
{
rows{
["2","xxx","yyyy"],
["3","xxx","yyyy"],
["4","xxx","yyyy"],
}
}
I am using $.rows to get all the rows. as well I am giving $.rows[0].[1] to get the value from 1st row and 1st value..
I am trying to get the total number of rows using $.rows.size() or length. It is not following exception. How to get the number of rows?
Exception: Options AS_PATH_LIST and ALWAYS_RETURN_LIST are not allowed
when using path functions!
Given the following JSON:
{
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
If I add JSON Path Extractor as a child of the sample which returns the above JSON and configure it like:
Reference Name: arraySize
JSONPath Expression: $..cars.length()
I am able to see the following variables in the View Results Tree listener:
arraySize=[3]
arraySize_1=3
arraySize_matchNr=1
Which seems to be something you're looking for.
You can install JSON Path Extractor along with JSON Path Assertion using JMeter Plugins Manager