How to find json array length in json extractor - json

Im using the following JSON and query to calculate the array length in the JMeter json extractor.
{
"data": {
"modal": "HJ",
"technicalid": "e492fc62-a886-67a461b76de8",
"viewModel": {
"series": [
{
"name": "H_0_G_0_R_0",
"UID": "J_0_G_0_R_0",
"description": "Test1",
"type": "series",
"groups": [
{
"name": "H_0_G_0",
"UID": "G_0_G_0",
"description": "Group 1",
"type": "group"
}
],
"postProcessing": null
}
]
},
"status": "success"
},
"success": true,
"statusCode": 200,
"errorMessage": ""
}
Here is the query.
data.Model.series[0].groups.length
This is working fine in the online jsonquerytool. When I use this query in the JMeter json extractor, it is returning null. I assume this is because it is returning an integer because other similar queries which are returning strings are working fine with json extractor . How to find the array length in JMeter json extractor?

Why JSON extractor to calculate the length? You could use a post processer. Like JSR223 post processer using groovy script.
import groovy.json.*
def response = prev.responseDataAsString ;
def json = new JsonSlurper().parseText(response) ;
def sizeResultPractitioners = json.data.viewModel.series[0].groups.size();
log.info("---------->"+sizeResultPractitioners);
I tried with your JSON response payload and also tried with modified response payload,
With modified response payload,

With JSON Extractor you can provide "Match No." as -1:
and the number of matches will be available as foo_matchNr JMeter Variable:
Alternative option is going for JSON JMESPath Extractor which provides length() function so you can get the size of the array as:
length(data.viewModel.series[0].groups)
or if you prefer pipe expressions
data.viewModel.series[0].groups | length(#)

Related

Jenkins Pipeline Error while trying to send JSON Payload after post success

I'm trying to send a custom JSON payload from my pipeline on Jenkins after the last successful stage, like this:
post {
success {
script {
def payload = """
{
"type": "AdaptiveCard",
"body": [
{
"type": "TextBlock",
"size": "Medium",
"weight": "Bolder",
"text": "SonarQube report from Jenkins Pipeline"
},
{
"type": "TextBlock",
"text": "Code was analyzed was successfully.",
"wrap": true,
"color": "Good",
"weight": "Bolder"
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.3"
}"""
httpRequest httpMode: 'POST',
acceptType: 'APPLICATION_JSON',
contentType: 'APPLICATION_JSON',
url: "URL",
requestBody: payload
}
}
}
}
But I get an error
Error when executing success post condition:
groovy.lang.MissingPropertyException: No such property: schema for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
I'm using the HTTP Request plugin available for Jenkins and the format of the JSON payload is correct for MS Teams.
The issue is actually a groovy syntax error. You can easily check this in something like https://groovy-playground.appspot.com/ by adding your def payload = ... statement.
There are multiple ways to get multiline strings in groovy:
triple single quoted string
triple double quoted string
slashy string
dollary slashy string
Apart from the single quoted string, they also have a secondary property which is interpolation
Notice how in the initial JSON payload, there's a "$schema" key? Using triple double quoted strings makes groovy want to find a schema variable and use it's value to construct that payload variable.
You have two separate solutions:
Use triple single quoted string - just update """ to '''
Escape the variable - just update "$schema" to "\$schema" (making $ a literal $ instead of it being used as an interpolation prefix)

How to loop through and assert JSON array objects in JMeter if they have the same name?

I have the below JSON response to be validated. I need to validate all the "createdDate" from all the Arrays irrespective. Is there any easy way to capture them or loop through them (since it has the same object name, but in different arrays) and put them in variables to do an assertion against their corresponding values from a JDBC response?
Right now I have used JSON Assertion for each and every "createdDate" using the JSON path to validate against the database value.
{
"someobject1": 123,
"Array1":
[
{
"someobject2": 2,
"createdDate": "2019-03-26T20:29:44.631+0000",
"someobject3": "SCRIPT1"
},
{
"someobject4": 3,
"createdDate": "2019-03-27T20:29:44.631+0000",
"someobject5": "SCRIPT2"
}
],
"Array2":
[
{
"someobject6": 4,
"createdDate": "2019-03-28T20:29:44.631+0000",
"someobject7": "SCRIPT3"
},
{
"someobject8": 5,
"createdDate": "2019-03-29T20:29:44.631+0000",
"someobject9": "SCRIPT4"
}
]
}
You can use JSON Assertion configured like:
Assert JSON Path Exists: $..createdDate
Expected Value: ["2019-03-26T20:29:44.631+0000","2019-03-27T20:29:44.631+0000","2019-03-28T20:29:44.631+0000","2019-03-29T20:29:44.631+0000"]
Full configuration:
More information:
JSON Path: Deep Scan Operator
JSON Path Examples
JMeter's JSON Path Extractor Plugin - Advanced Usage Scenarios

jmeter - How to format json in body data (extracted from regular expression)

I'm trying strong text to extract json with regular extraction then post it in the next request body data with formatted json. For the json that I extracted, they are not formatted and I'm just wondering if there is any function or way to format it?
Get request with regular expression extractor (extracted the bold section)
{
"groupedData": [{
"key": "FirstItem",
"count": 1,
"groupID": 1,
"items": [{
**"keyID": 97215,
"film": {
"name": xxxx,
"id": xxx,
"vendorID": 0,
"type": "PG",
"xxxx": xxx
},
"subGroups": null**
}],
"totalRows": 1
}]
}
Post in the next request with extracted data (JSON data extracted from above request with regular expression is appearing as whole string and just wondering how can i format in this body data?)
{
"keyID": 123,
"name": "SYSGEN",
"period": {
"keyID": 427,
},
"periodID": 427,
"items": [{
**${JSON}**
}],
"group": 0,
"selRow": false,
"rowId": 1,
"$rowState": {
"invalid": false,
},
"XXXX": XXXX,
}],
"ZZZZZZ": "ZZZZZ"
}
You can format the JSON using __groovy() function, i.e.
If you have a JMeter Variable foo where the extracted JSON data is stored and refer to it as ${foo} in the HTTP Request
Replace your ${foo} variable reference with the following function:
${__groovy(groovy.json.JsonOutput.prettyPrint(vars.get('foo')),)}
That's it, the above Groovy expression will format the JSON which lives in ${foo} JMeter Variable
If you want to get response text between given boundaries use Boundary Extractor:
Left Boundary:
"items": [{
Right Boundary:
}],
You can also test it using View Results Tree
The Boundary Extractor Tester only works for text responses. It shows the plain text in the upper panel. The "Test" button allows the user to apply the Boundary Extractor query to the upper panel and the results will be displayed in the lower panel.

How to Retrieve and Query JSON type fields in Apache Solr 6.5

My Goal is to retrieve JSON type fields in an Solr index and also perform search queries on such fields.
I have the following documents in Solr Index and using the auto generated schema utilizing schemaless feature in Solr.
POST http://localhost:8983/solr/test1/update?commitWithin=1000
[
{"id" : "1", "type_s":"book", "title_t" : "The Way of Kings", "author_s" : "Brandon Sanderson",
"miscinfo": {"provider": "orielly", "site": "US"}
},
{"id" : "2", "type_s":"book", "title_t" : "The Game of Thrones", "author_s" : "James Sanderson",
"miscinfo": {"provider": "pacman", "site": "US"}
}
]
I see the JSON types are stored as strings in the schemaField type as seen in the output for following
GET http://localhost:8983/solr/test1/schema/fields
{
"name":"miscinfo",
"type":"strings"}
I had tried using srcField as mentioned in this post. However, a query to retrieve json type returns empty response. Below are the GET request used for the same
GET http://localhost:8983/solr/test1/select?q=1&fl=miscinfo&wt=json
GET http://localhost:8983/solr/test1/select?q=1&fl=miscinfo,source_s:[json]&wt=json
Also, the search queries for values inside JSON type fields return empty response
http://localhost:8983/solr/test1/select?q=pacman&wt=json
{
"responseHeader": {
"status": 0,
"QTime": 0,
"params": {
"q": "pacman",
"json": "",
"wt": "json"
}
},
"response": {
"numFound": 0,
"start": 0,
"docs": []
}
}
Please help in searching object types in Solr.
Have you checked this: https://cwiki.apache.org/confluence/display/solr/Response+Writers
JSON Response Writer A very commonly used Response Writer is the
JsonResponseWriter, which formats output in JavaScript Object Notation
(JSON), a lightweight data interchange format specified in specified
in RFC 4627. Setting the wt parameter to json invokes this Response
Writer. Here is a sample response for a simple query like
q=id:VS1GB400C3&wt=json:

Parsing and manipulating json in Scala

I have this JSON that is returned from a REST-service I'm using.
{
"id": "6804",
"signatories": [
{
"id": "12125",
"fields": [
{
"type": "standard",
"name": "fstname",
"value": "John"
},
{
"type": "standard",
"name": "sndname",
"value": "Doe"
},
{
"type": "standard",
"name": "email",
"value": "john.doe#somwhere.com"
},
{
"type": "standard",
"name": "sigco",
"value": "Company"
}
]
}
]
}
Currently I'm looking into a way to parse this with json4s, iterating over the "fields" array, to be able to change the property "value" of the different objects in there. So far I've tried a few json libs and ended up with json4s.
Json4s allows me to parse the json into a JObject, which I can try extract the "fields" array
from.
import org.json4s._
import org.json4s.native.JsonMethods._
// parse to JObject
val data = parse(json)
// extract the fields into a map
val fields = data \ "signatories" \ "fields"
// parse back to JSON
println(compact(render(fields)))
I've managed to extract a Map like this, and rendered it back to JSON again. What I can't figure out though is, how to loop through these fields and change the property "value" in them?
I've read the json4s documentation but I'm very new to both Scala and it's syntax so I'm having a difficult time.
The question becomes, how do I iterate over a parsed JSON result, to change the property "value"?
Here's the flow I want to achieve.
Parse JSON into iterable object
Loop through and look for certain "names" and change their value, for example fstname, from John to some other name.
Parse it back to JSON, so I can send the new JSON with the updated values back.
I don't know if this is the best way to do this at all, I'd really appreciate input, maybe there's an easier way to do this.
Thanks in advance,
Best regards,
Stefan Konno
You can convert the json into an array of case class which is the easiest thing to do. For example: you can have case class for Fields like
case class Field(`type`: String, name: String, value: String)
and you can convert your json into array of fields like read[Array[Field]](json) where json is
[
{
"type": "standard",
"name": "fstname",
"value": "John"
},
...
]
which will give you an array of fields. Similarly, you can model for your entire Json.
As now you have an array of case classes, its pretty simple to iterate the objects and change the value using case classes copy method.
After that, to convert the array of objects into Json, you can simply use write(objects) (read and write functions of Json4s are available in org.json4s.native.Serialization package.
Update
To do it without converting it into case class, you can use transformField function
parse(json).transformField{case JField(x, v) if x == "value" && v == JString("Company")=> JField("value1",JString("Company1"))}