how get all id from json to array on other variables - jmeter - arrays

I have two JSON. In the both I have name. How can I get names from first JSON and add to array? Later I want do this same with second JSON later i want both array compare? How can I do this?
jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
for example I want:
a = [doug, dofug] b = [goud, doaaug]
and later check if these are the same arrays
i don't know how can i do this in jmeter, help

To convert one array to another:
Add JSR223 PostProcessor as a child of the request which returns first JSON Array
Put the following code into "Script" area:
def builder = new groovy.json.JsonBuilder()
builder(com.jayway.jsonpath.JsonPath.read(prev.getResponseDataAsString(),'$..name').collect())
vars.put('array1', builder.toPrettyString())
That's it, you should be able to access the newly generated JSON Array as ${array1} where required
Repeat the same steps for the second JSON array.
There are several options on how to compare 2 JSON entities, depending on what you're trying to achieve you can go for:
Response Assertion
a JSR223 Assertion and a 3rd-party library like:
Jackson
Gson
JSONassert

Related

Is it possible to use the range function in Azure Data Factory and add ID's to the result?

Let's say I want to use the range function (inside a ForEach loop) in Azure Data Factory to create an array which consists of integers. These integers represent API pages related to some ID which was given to us as a parameter in the ForEach loop.
I would use it like #range(1, int(varMaxApiPages)).
This gives me what I expect; an array of integers:
[1, 2, 3]
But would it be possible to append the related ID to these integers? So the result would be something like: [{"someID", 1},{"someID", 2},{"someID", 3}]?
Such as:
def appendToArray(varMaxApiPages):
arr1 = list(range(varMaxApiPages))
json_array = [];
for item in arr1:
jsonObejct = {"someID",item}
json_array.append(jsonObejct)
for item in json_array:
print(item)
appendToArray(3)
The correct json array should look like this [{"someID": 1},{"someID": 2},{"someID": 3}], we can achieve that. If you don’t want the colon, you can think of a way to replace it.
My debug result is as follows:
I declared 3 array type variables. Variable res is used to review the debug result.
In Set variable1 activity, assign the value to it via #range(1,3).
Then Foreach the arr1.
Inside Foreach activity, we can use Append variable activity, add expression #json(concat('{"someID":',item(),'}')). It will convert json string to json Object and append to the array jsonArray.
Outside Foreach activity, assign the value of array jsonArray to array res to review the result, you can omit this step and use array jsonArray directly.
That's all.

Jmeter: Saving response of a sampler inside a loop controller in a array variable

--Loop_controller
|--Http_Request_Sampler_One
--Http_Request_Sampler_Two
I have a sampler (Http_Request_Sampler_One) with a response body {"id": "12345"}.
This sampler is in a loop controller, which will run 3 times for example.
I want a string array variable named Ids to hold all the id.
in the form Ids = ["12345", "23421", "43546"]
I want to use this Ids variable in Http_Request_Sampler_Two once the loop controller ends.
Note: I'm able to extract the id from the response body using JSON-extractor, I'm more interested in knowing a way to push it in an array after each iteration ends.
Add JSR223 PostProcessor as a child of your Http_Request_Sampler_One
Put the following code into "Script" area
if (vars.get('__jm__Loop Controller__idx') == '0') {
def Ids = []
Ids.add(new groovy.json.JsonSlurper().parse(prev.getResponseData()).id)
vars.put('Ids', new groovy.json.JsonBuilder(Ids).toPrettyString())
}
else {
def Ids = new groovy.json.JsonSlurper().parseText(vars.get('Ids'))
Ids.add(new groovy.json.JsonSlurper().parse(prev.getResponseData()).id)
vars.put('Ids', new groovy.json.JsonBuilder(Ids).toString())
}
That's it, once your Loop Controller finishes you will get all the "ids" extracted from the Http_Request_Sampler_One as ${Ids} JMeter Variable.
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Chef - Ruby - How to extract values from a nested array/list

I'm using this json content (I'm open to suggestions on better formatting here):
{"forwardingZones": [{"name": "corp.mycompany.com","dnsServers": ["192.168.0.1","192.168.0.2"]}]}
Note: we may add more items to this list as we scale out, both more IPs and more names, hence the "join(',')" in the end of the code below.
And I'm trying to loop through it to get this result:
corp.mycompany.com=192.168.0.1;192.168.0.2
Using this code:
forward_zones = node['DNS']['forward_zones'].each do |forwarded_zone|
forwarded_zone_name = forwarded_zone['name']
forwarded_zone_dns_servers = forwarded_zone['dns_servers'].join(';')
"#{forwarded_zone_name}=#{forwarded_zone_dns_servers}"
end.join(',')
This is the result that I get:
{"dnsServers"=>["192.168.0.1", "192.168.0.2"], "name"=>"corp.mycompany.com"}
What am i doing wrong...?
x.each returns x. You want x.map.

Javascript / Jquery multidimensional array

I Have an array like this :
var ProG = [[1,0,0,0],[1,0,0,0],[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]];
I have also a hidden field (id=prog-id) in a form, that I use to send this array to the server:
jQuery('#prog-id').val(JSON.stringify(ProG));
the sent array become:
"prog": "[[1,0,0,0],[1,0,0,0],[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]"
the next code take the array and other data from the server with ajax request:
value is the data that come from ajax
I create an object:
var obj = jQuery.parseJSON(value);
Now the problem:
if I console.log(ProG) the array before sent I get:
Array[7]0: Array[4]1: Array[4]2: Array[4]3: Array[4]4: Array[4]5: Array[4]6: Array[4]length: 7__proto__: Array[0]
that is ok.
But If I do the same after getting array I receive this:
[[1,0,0,0],[1,0,0,0],[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
How can I put the received array in original format?
Ok I find out:
jQuery.parseJSON(ProG).

JMeter: How to count JSON objects in an Array using jsonpath

In JMeter I want to check the number of objects in a JSON array, which I receive from the server.
For example, on a certain request I expect an array with 5 objects.
[{...},{...},{...},{...},{...}]
After reading this: count members with jsonpath?, I tried using the following JSON Path Assertion:
JSON Path: $
Expected value: hasSize(5)
Validate against expected value = checked
However, this doesn't seem to work properly. When I actually do receive 5 objects in the array, the response assertion says it doesn't match.
What am I doing wrong?
Or how else can I do this?
Although JSONPath Extractor doesn't provide hasSize function it still can be done.
Given the example JSON from the answer by PMD UBIK-INGENIERIE, you can get matches number on book array in at least 2 ways:
1. Easiest (but fragile) way - using Regular Expression Extractor.
As you can see, there are 4 entries for category like:
{ "category": "reference",
{ \"category\": \"fiction\"
...
If you add a Regular Expression Extractor configured as follows:
It'll capture all the category entries and return matches number as below:
So you will be able to use this ${matches_matchNr} variable wherever required.
This approach is straightforward and easy to implement but it's very vulnerable to any changes in the response format. If you expect that JSON data may change in the foreseeable future continue with the next option.
2. Harder (but more stable) way - calling JsonPath methods from Beanshell PostProcessor
JMeter has a Beanshell scripting extension mechanism which has access to all variables/properties in scope as well as to the underlying JMeter and 3rd-party dependencies APIs. In this case you can call JsonPath library (which is under the hood of JsonPath Extractor) directly from Beanshell PostProcessor.
import com.jayway.jsonpath.Criteria;
import com.jayway.jsonpath.Filter;
import com.jayway.jsonpath.JsonPath;
Object json = new String(data);
List categories = new ArrayList();
categories.add("fiction");
categories.add("reference");
Filter filter = Filter.filter(Criteria.where("category").in(categories));
List books = JsonPath.read(json, "$.store.book[?]", new Filter[] {filter});
vars.put("JSON_ARRAY_SIZE", String.valueOf(books.size()));
The code above evaluates JSONPath expression of $.store.book[?] against parent sampler response, counts matches number and stores it into ${JSON_ARRAY_SIZE} JMeter Variable
which can later be reused in an if clause or an assertion.
References:
JMeter – Working with JSON – Extract JSON response
JMeter's User Manual Regular Expressions entry
JSON Path Documentation and Examples
How to use BeanShell: JMeter's favorite built-in component
This is not possible with the plugin you are using (JMeter-plugins).
But it can be done with JSON Extractor since JMeter 3.0, this plugin has been donated by UbikLoadPack (http://jmeter.apache.org/changes_history.html)
Example:
Say you have this JSON that contains an array of books:
{ "store": {"book": [
{ "category": "reference","author": "Nigel Rees","title": "Sayings of the Century","price": 8.95},
{ "category": "fiction","author": "Evelyn Waugh","title": "Sword of Honour","price": 12.99},
{ "category": "fiction","author": "Herman Melville","title": "Moby Dick","isbn": "0-553-21311-3","price": 8.99},
{ "category": "fiction","author": "J. R. R. Tolkien","title": "The Lord of the Rings","isbn": "0-395-19395-8","price": 22.99}
],
"bicycle": {"color": "red","price": 19.95}} }
To have this count:
1/ Add JSON Extractor:
The count will be then available bookTitle_matchNr which you can access through:
${bookTitle_matchNr}
Running this Test Plan would display this:
As you can see, Debug Sampler-${bookTitle_matchNr} shows Debug Sampler-4

Resources