I have a JSON response in SoapUI that looks like this:
{
"civilite" : "1" ,
"nom" : "Fitz",
"prenom" : "Quinn",
"dateN" : "07/10/1953"
}
But I want to use JsonPath to retrieve only a part of this data, so I could have something like this:
{
"nom" : "Fitz",
"prenom" : "Quinn"
}
Is there a way to apply a JsonPath expression to retrieve this information?
For the first request step, add Script Assertion and use below script. The script extract the nom and prenom values and set them at test case level custom properties with given property names. With Script Assertion, an additional Groovy Script test step can be avoided.
Then in the next test step, use property expansion, so that those values will be replaced automatically with actual values by soapui.
Script Assertion:
//Check if the response is non empty or null
assert context.response
//Parse Json
def parsedJson = new groovy.json.JsonSlurper().parseText(context.response)
log.info "Nom: ${parsedJson.nom}"
log.info "Prenom: ${parsedJson.prenom}"
//assert if nom and prenom are not empty
assert parsedJson.nom, "nom is null or empty in the response"
assert parsedJson.prenom, "prenom is null or empty in the response"
//Set the retrieved values at test case level properties NOM, PRENOM
context.testCase.setPropertyValue('NOM', parsedJson.nom as String)
context.testCase.setPropertyValue('PRENOM', parsedJson.prenom as String)
Change 2nd step request content as below with Property Expansion
{
"nom" : "${#TestCase#NOM}",
"prenom" : "${#TestCase#PRENOM}"
}
Try this
input = {
"civilite" : "1" ,
"nom" : "Fitz",
"prenom" : "Quinn",
"dateN" : "07/10/1953"
}
output ={};
input.reduce(function (result, currentObject) {
output = {
nom: currentObject.nom,
prenom: currentObject.prenom
};
return output;
}, output);
Related
I have a JSON object:
{
"login_name":"hello#gmail.com",
"login_pass":"abc123",
"created_on":"2021-01-17 19:20:07",
"user_id":"1",
"active":"1"
}
I don't know how to access it because it doesn't have a name.
This is using Volley:
val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
{ response ->
val obj = JSONObject(response.toString()) // this works and outputs the JSON object
val test: JSONObject = obj.getJSONObject("login_name") // this doesn't work
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
},
{ error ->
Toast.makeText(this#Login, "Error!", Toast.LENGTH_LONG).show()
}
)
I also tried converting the Json object to an array but that didn't work either...
Looked at:
Get JSONArray without array name, How can i write Android Json parsing without array name
EDIT:
val obj = JSONObject(response)
That didn't work for me because:
None of the following functions can be called with the arguments supplied.
(String!) defined in org.json.JSONObject
((MutableMap<Any?, Any?>..Map<*, *>?)) defined in org.json.JSONObject
(JSONTokener!) defined in org.json.JSONObject
But after 2 days of trying, this worked... Didn't think I could just do that
val test = response.getString("login_name")
response is indeed a jsonObject, you could use it without know its name:
String login_name= response.getString("login_name");
You are all most doing it right. Ass i see you convert the object to a string, and thats why you cant access the data afterwards.
val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
{ response ->
val obj = JSONObject(response) // this works and outputs the JSON object
val test: JSONObject = obj.getJSONObject("login_name") // this doesn't work
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
},
{ error ->
Toast.makeText(this#Login, "Error!", Toast.LENGTH_LONG).show()
}
)
Try this, without the toString() function on response.
Example:
API A:
{
"customer":[
{
"name":"Jane",
"phone":"9999999",
"email":"jane#test.com"
},
{
"name":"John",
"phone":"8888888",
"email":"john#test.com"
},
{
"name":"Joe",
"phone":"7777777",
"email":"Joe#test.com"
}
]
}
Using the JSON extractor, I want to get the names of all the customers
so: Jane, John, Joe
How do I get these values and turn them into an array
[{"name":"Jane", "name":"John", "name":"Joe"}]
And pass it onto the next API?
Note: That it has to be dynamic so API A could show different 2 names or 1 name or more and needs to be adjusted into the array
First of all your [{"name":"Jane", "name":"John", "name":"Joe"}] is not a valid JSON, you can check it yourself:
so I strongly doubt that this is the string you need to generate.
So if you really need to construct this value you can do something like:
Add JSR223 PostProcessor as a child of the request which returns this "customers" data
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def payload = new StringBuilder()
payload.append('[{')
0.upto(response.customer.size - 1, { index ->
payload.append('"name": "').append(response.customer[index].name).append('"')
if (index != response.customer.size - 1) {
payload.append(',')
}
})
payload.append('}]')
vars.put('payload', payload as String)
Refer the generated value as ${payload} where required
Demo:
More information:
JsonSlurper
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
I want to update some values of below content which i believe a json file. This is the output of azure devops release definition and I need to reuse the content modifying some fields.
I can simply update values like id and name using these lines
$ReleaseDef.Name = $newReleaseName
$ReleaseDef.path = $folderQA
But I dont know how to update array fields like artifact and triggers. I can get values by calling $ReleaseDef.artifacts.sourceid
but can not set any values there , It throws errors like The property 'sourceid' cannot be found on this object. Verify that the
property exists and can be set.
Please suggest
source : userInterface
revision : 4
description :
createdBy : #{displayName=Jyotiprakash Nayak; url=https://azuredevopsdv
.ril.com/EntApps/_apis/Identities/2ca8bd5d-7797-4177-b7bb-2
6daa0d29ed9; _links=;
id=2ca8bd5d-7797-4177-b7bb-26daa0d29ed9;
uniqueName=domain\Jyotiprakash.Nayak; imageUrl=https://azuredev
opsdv.company.com/EntApps/_apis/GraphProfile/MemberAvatars/win.
Uy0xLTUtMjEtMjIwNzU5NTE2Ni03MjEyNTY2NjUtNTU2MTkwNDkyLTQ4NjY
yMw; descriptor=win.Uy0xLTUtMjEtMjIwNzU5NTE2Ni03MjEyNTY2NjU
tNTU2MTkwNDkyLTQ4NjYyMw}
createdOn : 2019-12-10T09:11:11.057Z
modifiedBy : #{displayName=Jyotiprakash Nayak; url=https://azuredevopsdv
.company.com/EntApps/_apis/Identities/2ca8bd5d-7797-4177-b7bb-2
6daa0d29ed9; _links=;
id=2ca8bd5d-7797-4177-b7bb-26daa0d29ed9;
uniqueName=Domain\Jyotiprakash.Nayak; imageUrl=https://azuredev
opsdv.comapny.com/EntApps/_apis/GraphProfile/MemberAvatars/win.
Uy0xLTUtMjEtMjIwNzU5NTE2Ni03MjEyNTY2NjUtNTU2MTkwNDkyLTQ4NjY
yMw; descriptor=win.Uy0xLTUtMjEtMjIwNzU5NTE2Ni03MjEyNTY2NjU
tNTU2MTkwNDkyLTQ4NjYyMw}
modifiedOn : 2019-12-13T09:16:13.463Z
isDeleted : False
variables :
variableGroups : {}
environments : {#{id=7; name=Stage 1; rank=1; owner=; variables=;
variableGroups=System.Object[]; preDeployApprovals=;
deployStep=; postDeployApprovals=;
deployPhases=System.Object[]; environmentOptions=;
demands=System.Object[]; conditions=System.Object[];
executionPolicy=; schedules=System.Object[];
currentRelease=; retentionPolicy=; processParameters=;
properties=; preDeploymentGates=; postDeploymentGates=;
environmentTriggers=System.Object[]; badgeUrl=https://azure
devopsdv.comapny.com/EntApps/_apis/public/Release/badge/e0b1a36
0-01a5-4eea-af57-b2a461559ac9/7/7}}
artifacts : {#{sourceId=e0b1a360-01a5-4eea-af57-b2a461559ac9:48;
type=Build; alias=_eCAM-Team-CI; definitionReference=;
isPrimary=True; isRetained=False}}
triggers : {#{artifactAlias=_eCAM-Team-CI;
triggerConditions=System.Object[];
triggerType=artifactSource}}
releaseNameFormat : Release-$(rev:r)
tags : {}
pipelineProcess : #{type=designer}
properties : #{DefinitionCreationSource=}
id : 7
name : Release-Template-1
path : \QA
projectReference :
url : https://azuredevopsdv.company.com/EntApps/e0b1a360-01a5-4eea-af
57-b2a461559ac9/_apis/Release/definitions/7
_links : #{self=; web=}
These attributes contain hash table values.
You should be able to update by specifying the key and its new value like so:
$ReleaseDef.artifacts["sourceid"] = "someValueHere"
Thanks all for your valuable helps, I finally made it work through some foreach loops.
```$artifact = $json.artifacts
foreach ($value in $artifact)
{
$value.alias = "_$newReleaseName"
$value.sourceId = "$($projectid):$($BuildID)"
}
foreach ($triggervalue in $snapshot.triggers)
{
$triggervalue.artifactAlias = "_$newReleaseName"
}```
I encounter an issue using Gatling EL in ELFileBody.
I have the following exec :
exec(myFunction("${myEmail}", otherParameters))
and the function :
def myFunction((email: String) = {
exec((s: Session) => s.set("email", email))
.exec(http("MyFunction")
.put("/myUrl")
.headers(Headers.basic_headers_json)
.body(ElFileBody("LinkToMyJsonFile"))
.asJson
.check(status.is(200)))
}
my myEmail is set in session. Yet, when the exec runs myFunction, the variable is replaced in the json by "${myEmail}" instead of beeing evaluated.
Have you an idea how I can resolve it be able to pass myEmail session variable in the exec through myFunction?
Thanks a lot in advance
JF
your function takes a string and you are then putting that string into a session variable - so when you pass in "${myEmail}" gatling is putting that string literal into the session var. So when gatling does the substitution in the ELFile body it's using exactly what you've specified.
I'm assuming you already have the email you want in the ${myEmail} session var - why not just edit the file to use ${myEmail} in place of "${email}"?
a more idiomatic approach would be to pass in an Expression[String], validate it and set the result into the ${email} var
def myFunction((email: Expression[String]) = {
exec((s: Session) => email.apply(s) match {
case Success(address) => s.set("email", address)
case Failure(error) => {
println(s"There was an error: $error")
s
}
}
...
This will retrieve the value of ${myEmail} if there is one or just the string literal if that's the case, and put it in the ${email} var. The error would be thrown if you provided a session var for which there was no value
So, I get some JSON values from the server but I don't know if there will be a particular field or not.
So like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
}
And sometimes, there will be an extra field like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited",
"club":"somevalue"
}
I would like to check if the field named "club" exists so that at parsing I won't get
org.json.JSONException: No value for club
JSONObject class has a method named "has":
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
Returns true if this object has a mapping for name. The mapping may be NULL.
You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.
if (json.has("status")) {
String status = json.getString("status"));
}
if (json.has("club")) {
String club = json.getString("club"));
}
You can also check using 'isNull' - Returns true if this object has no
mapping for name or if it has a mapping whose value is NULL.
if (!json.isNull("club"))
String club = json.getString("club"));
you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also
use optString instead of getString:
Returns the value mapped by name if it exists, coercing it if
necessary. Returns the empty string if no such mapping exists
just before read key check it like before read
JSONObject json_obj=new JSONObject(yourjsonstr);
if(!json_obj.isNull("club"))
{
//it's contain value to be read operation
}
else
{
//it's not contain key club or isnull so do this operation here
}
isNull function definition
Returns true if this object has no mapping for name or
if it has a mapping whose value is NULL.
official documentation below link for isNull function
http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)
You can use has
public boolean has(String key)
Determine if the JSONObject contains a specific key.
Example
JSONObject JsonObj = new JSONObject(Your_API_STRING); //JSONObject is an unordered collection of name/value pairs
if (JsonObj.has("address")) {
//Checking address Key Present or not
String get_address = JsonObj .getString("address"); // Present Key
}
else {
//Do Your Staff
}
A better way, instead of using a conditional like:
if (json.has("club")) {
String club = json.getString("club"));
}
is to simply use the existing method optString(), like this:
String club = json.optString("club);
the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.
Try this:
let json=yourJson
if(json.hasOwnProperty(yourKey)){
value=json[yourKey]
}
Json has a method called containsKey().
You can use it to check if a certain key is contained in the Json set.
File jsonInputFile = new File("jsonFile.json");
InputStream is = new FileInputStream(jsonInputFile);
JsonReader reader = Json.createReader(is);
JsonObject frameObj = reader.readObject();
reader.close();
if frameObj.containsKey("person") {
//Do stuff
}
Try this
if(!jsonObj.isNull("club")){
jsonObj.getString("club");
}
I used hasOwnProperty('club')
var myobj = { "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
};
if ( myobj.hasOwnProperty("club"))
// do something with club (will be false with above data)
var data = myobj.club;
if ( myobj.hasOwnProperty("status"))
// do something with the status field. (will be true with above ..)
var data = myobj.status;
works in all current browsers.
You can try this to check wether the key exists or not:
JSONObject object = new JSONObject(jsonfile);
if (object.containskey("key")) {
object.get("key");
//etc. etc.
}
I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces {} and using has(String key) doesn't make any sense.
So you can directly write if (jsonObject.length() > 0) and do your things.
Happy learning!
You can use the JsonNode#hasNonNull(String fieldName), it mix the has method and the verification if it is a null value or not