How to save a JSON-object and use it in another request? - json

i'm currently trying to set up some JMeter testplans. I am pretty new to this (started a week ago) and don't have much programming experience either, so i hope you could help me in this case.
I already set up some http requests and have some simple JSON Extractor post processors to save some of the variables and use them with the "${variable}" notation.
But now i need to save and modify an object from a response to use that in the next http request.
My respose is a extremely big JSON object and the part im interested in looks something like this:
{
"payload": {
"workspace": {
"resultInstance": [
[{"part": "1"...}],
[{"part": "2"...}],
...
[{"part": "20"...}]
]
}
}
}
Note that for whatever reason these objects {"part":"1"...} are inside a nested array. And they are also pretty big.
I would like to safe those objects in a variable to use them in my next http request which should looks like this:
{
"instanceChange": {
"functionChecks": [
{"part": "1"...},
{"part": "2"...},
...
{"part": "20"...}
]
}
}
So what im really trying to find is a way to save all of the possible objects inside the nested array "resultInstance" and put them inside the non nested array "functionChecks".
I already looked inside the JMeter documentation but because of my poor programming background i cant find a way to realize this.
I think i need something like the JSR223 PostProcessor and "simply go through the resultInstance-array and use smth. like an getObject() on these", but i cant figure out the code i need and if its even possible to safe objects in variables in Jmeter.
Im pretty thankful for every bit of help or advice :).
Thanks in advance,
aiksn

Add JSR223 PostProcessor as a child of the request which returns the JSON response
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def request = ['instanceChange': ['functionChecks': response.payload.workspace.resultInstance]]
vars.put('request', new groovy.json.JsonBuilder(request).toPrettyString())
That's it, you should be able to refer the generated request body as ${request} where required
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

let response ={
"payload": {
"workspace": {
"resultInstance": [
[{"part": "1"...}],
[{"part": "2"...}],
...
[{"part": "20"...}]
]
}
}
};
let requestObj={
"instanceChange": {
"functionChecks": [
]
}
};
response.payload.workspace.resultInstance.forEach(myFunction);
myFunction(item, index) {
requestObj.instance.functionsCheck.push(item[0]);
}

Related

How to parse Json with Array list

I have below response from an API get call.
How do i read the value of dummyId and testcontactId. Below is the sample response:
{
"pageCount":1,
"pageIndex":0,
"pageSize":200,
"totalCount":1,
"dto":{
"data":[
{
"callDuration":"0:00:07",
"dummyId":20,
"testcontactId":"3002",
"id":54
}
],
"columns":[
{
"fieldName":"test1",
"displayName":"test Id",
"show":true,
"sortable":true,
"fieldType":"string",
"order":1
}
]
}
}
I can't place a comment to ask what language you're using, Here is how you'd do it in JavaScript
Parse your API Result to a Object with var data = JSON.parse() JSON.parse()
Then you can just go data.dto.data[0].dummyId
Since dto.data is an array, You can just use the indexes to access each option.
if you need to find specific values, You might want to take a look at Array.find
In the future, Please add a tag with your programming language and things you've tried.

Returning a specific JSON object using Express

So let's say I've got a massive JSON file, and the general structure is roughly like so:
{
"apples": { complex object },
"oranges": { complex object },
"grapes": { complex object }
}
Is there some way to specifically target an object to return while using express? As in, say, if someone made a simple get request to my server, it'd return specifically the given object(s). I know the syntax and concept is completely wrong in this instance but for lack of a better way to say it, something like...
let testData = 'testdata.json';
app.get('/thing', res => {
res.json(testData.oranges);
}
I know you can return the entire file, but that adds a good amount of loading time in this instance, and is impractical in this particular case.
Or, alternatively - would it be better to have node parse the JSON file and split it into an apples.json, oranges.json, etc files to use? Trying to understand A, the best practice for doing something like this, and B, the most effective way to translate this into a practical application for a medium sized project.
Any thoughts or advice along this line - even if it's a library recommendation - would be greatly appreciated.
It should work if you make a POST request caring the payload of the specific 'thing', and then returning an object based on that thing. Example:
let testData = {
"apples": { complex object },
"oranges": { complex object },
"grapes": { complex object }
};
app.post('/route', (req, res) => {
thing = req.body.thing;
res.json(testData[thing]);
}
This is a GET request for some data and essentially since the JSON file can be used as a key/value store to query for the desired response data.
Assuming the query parameter for specifying the desired key for the object to return is part then the following example would work:
const testData = require('./testdata.json');
app.get('/thing', (req, res) => res.json(testdata[req.query.part]);
Querying for /thing?part=apples would return testdata.apples in the response.

How to store entire response and update it for next rest call using Jmeter

Question: How to extract entire restAPI response and modify it with some values and use the updated response for sub-sequent rest call. I am using Jmeter
Question Scenario:
I have one POST call ex: "/check1/id1/post"
POST body :
{
"test":"rest",
"check" :{
"id":1,
"name": "xyz"
}
}
POST call RESPONSE :
{
"test":"rest",
"check" :{
"id":1,
"name": "xyz"
"status":"updated"
}
}
=====================================================================
QUESTION: Now, I have to use entire above RESPONSE in next POST Call body as below, BUT, I wanted to update "id" value as 2 and then need to POST rest call.
REST CALL: ------ > "/check1/id2/post"
POST BODY as below : ------->
{
"test":"rest",
"check" :{
"id":2,
"name": "xyz"
"status":"updated"
}
}
=============================================================
Can anyone please guide on this? , I am clueless about how to solve this issue?, I need to solve this using Jmeter.
To store entire response:
add Regular Expression Extractor as a child of the request which response you want to capture
configure it as follows:
Reference name: anything meaningful, i.e. response
Regular Expression: (?s)(^.*)
Template: $1$
To replace 1 with 2 you can go for __strReplace() function like ${__strReplace(${response},1,2,)}. Note that you need to install Custom JMeter Functions bundle using JMeter Plugins Manager in order get it.
You can do this using beanshell or JSR223 PreProcessor
Assuming a valid JSON
{
"test":"rest",
"check" :{
"id":1,
"name": "xyz",
"status":"updated"
}
}
Here are the steps
Add a JSR223 preprocessor to the 2nd post request.
Add the following code to the preprocessor
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def slurped = new JsonSlurper().parse(prev.getResponseData())
def builder = new JsonBuilder(slurped)
builder.content.check.id = '2'
vars.put("POSTDATA",builder.toPrettyString())
Above code will update ID value with 2 and stores the JSON in POSTDATA , you can use ${POSTDATA} to post the JSON FILE
In my pre processor i'm saving the response using prev.getResponseData() , that means this pre processor must included with the sampler right next to the first sampler.
For more information on beanshell Please follow this link

Converting velocity response to JSON

I am using struts 2 and velocity templates to generate JSON response.
Now the catch is the response is not generated using some velocity JSON plugin
it's just a String that comes out once velocity is done with its parsing and rendering of
response, and on client side I do eval to get the response from string to JSON.
What I really need is some solution on velocity's or struts' side where, once the result is
generated by velocity, the framework should call my API where I can convert the response output of vm file into JSON using my own logic. How do achieve this?
For example:
On browser using JavaScript I have designed a tree widget that I use for displaying comments in tree structure.
Say user clicks on comments button.
My UI widget will fire an AJAX to get data for comments.
This request is intercepted by STRUTS 2 framework.
It will call, say, getComments() action API and will populate an arrayList with comment object say cmt.
Now the response is handled by a velocity template(*.vm).
Now in vm I am writing code like this:
{ "CommentsData" : [
#set($sep="")
#foreach($c in $cmt)
$sep
{
"commentText" : $c.getText()
}
#set($sep=",")
#end
}
Now the final response may turn out like this:
{ "CommentsData" : [
{
"commentText" : "This is comment 1"
},
{
"commentText" : "This is comment 2"
},
{
"commentText" : "This is comment 3"
},
{
"commentText" : "This is comment 4"
}`
]
}
Now this may look like JSON, but its not strict JSON; I mean if I miss
some , somewhere then on client side in JavaScript my eval might fail or JSON.parse()
will fail, but on velocity template I have now clue if JSON is malformed.
So once the above velocity template is generated I need some control, where I can write some Java code to do some validations on the response.
I see that my approach to use velocity template to generate JSON output (actully a String that looks like JSON) may be wrong. But still I need to handle the response of every velocity template I have written.
Not sure how you are using velocity. We don't use velocity when outputting JSON; we just create a JSON convertible object and output it directly from controllers using response.write(jsonObject.toJson()). This way, proper JSON is always generated.

Provide JSON as data for rich:extendedDataTable

I am implementing a full text search in my project and for that the result of search comes from SOLR server as JSON.
Is it possible to provide JSON for data or value attribute of the richfaces component extendedDatatTable or simple dataTable.
Resultant JSON would look something like :
`resultObj = {
"numberOfResults":25,
"results":[
{
"instanceId":100,
"inj_Name":"Inj4",
"i_IdentificationNumber":127,
"noz_Name":"Nozzle4",
"n_IdentificationNumber":460,
"thr_Name":"Throttleplate4",
"t_IdentificationNumber":0,
"act_Name":"Atuator4",
"a_IdentificationNumber":781
},
{
"instanceId":100,
"inj_Name":"Inj4",
"i_IdentificationNumber":127,
"noz_Name":"Nozzle4",
"n_IdentificationNumber":460,
"thr_Name":"Throttleplate4",
"t_IdentificationNumber":0,
"act_Name":"Atuator4",
"a_IdentificationNumber":781
} ]
};
`
Regards,
Satya
As far as I know, no you can't. Your best bet would be to reflect this data into a List of Java objects using Gson and then use that list as a data source.