How to remove brackets from JSON? - json

I have a groovy script that I want to return userDefinedErrorText. The issue I am having is that when parse my JSON I am having my failedForm variable equal [Failed] instead of "Failed".
If I remove the first pair of [] from my JSON input, I get the correct "Failed".
Is there a way to remove [] from the input JSON?
My Groovy
def json = new JsonSlurper().parseText( aInputJson )
failedForm = json?.userDefinedErrorText
if( failedForm == "Failed" ) {
resultMessage = "false"
}
JSON
[
{
"step": "abcd",
"message": {
"ServiceRequest: abc": {
"App Stack Form Exception": {
"Expecting Form": "P",
"Resulting Form": "P"
},
"JAS Response": {
"fs_P": {
"title": "I",
"data": {},
"errors": [
{
"CODE": "799L",
"TITLE": "Error: Invalid Long Address Number",
"ERRORCONTROL": "15",
"DESC": "CAUSE . . . . The long address number entered is not found in the Address Book\\u000a Master file (F0101).\\u000aRESOLUTION. . Enter a valid long address number.",
"MOBILE": "The long address number entered is not found in the Address Book\\u000a Master file (F0101)."
}
],
"warnings": []
},
"stackId": 12,
"stateId": 5,
"rid": "8f4",
"currentApp": "P",
"timeStamp": "2022-04-22:11.25.03",
"sysErrors": []
}
}
},
"timeStamp": "2022-04-22T11:25:03.235-0400",
"userDefinedErrorText": "Failed"
}
]

The issue I am having is that when parse my JSON I am having my
failedForm variable equal [Failed] instead of "Failed".
The following should work:
String jsonString = '''
[
{
"step": "abcd",
"message": {
"ServiceRequest: abc": {
"App Stack Form Exception": {
"Expecting Form": "P",
"Resulting Form": "P"
},
"JAS Response": {
"fs_P": {
"title": "I",
"data": {},
"errors": [
{
"CODE": "799L",
"TITLE": "Error: Invalid Long Address Number",
"ERRORCONTROL": "15",
"DESC": "CAUSE . . . . The long address number entered is not found in the Address Book\\\\u000a Master file (F0101).\\\\u000aRESOLUTION. . Enter a valid long address number.",
"MOBILE": "The long address number entered is not found in the Address Book\\\\u000a Master file (F0101)."
}
],
"warnings": []
},
"stackId": 12,
"stateId": 5,
"rid": "8f4",
"currentApp": "P",
"timeStamp": "2022-04-22:11.25.03",
"sysErrors": []
}
}
},
"timeStamp": "2022-04-22T11:25:03.235-0400",
"userDefinedErrorText": "Failed"
}
]'''
def json = new JsonSlurper().parseText(jsonString)
String value = json[0].userDefinedErrorText
assert value == 'Failed'

Related

How to get the All index values in Groovy JSON xpath

Please find the attached Groovy code which I am using to get the particular filed from the response body.
Query 1 :
It is retrieving the results when the I am using the correct Index value like if the data.RenewalDetails[o], will give output as Value 1 and if the data.RenewalDetails[1], output as Value 2.
But in my real case, I will never know about number of blocks in the response, so I want to get all the values that are satisficing the condition, I tried data.RenewalDetails[*] but it is not working. Can you please help ?
Query 2:
Apart from the above condition, I want to add one more filter, where "FamilyCode": "PREMIUM" in the Itemdetails, Can you help on the same ?
def BoundId = new groovy.json.JsonSlurper().parseText('{"data":{"RenewalDetails":[{"ExpiryDetails":{"duration":"xxxxx","destination":"LHR","from":"AUH","value":2,"segments":[{"valudeid":"xxx-xx6262-xxxyyy-1111-11-11-1111"}]},"Itemdetails":[{"BoundId":"Value1","isexpired":true,"FamilyCode":"PREMIUM","availabilityDetails":[{"travelID":"AAA-AB1234-AAABBB-2022-11-10-1111","quota":"X","scale":"XXX","class":"X"}]}]},{"ExpiryDetails":{"duration":"xxxxx","destination":"LHR","from":"AUH","value":2,"segments":[{"valudeid":"xxx-xx6262-xxxyyy-1111-11-11-1111"}]},"Itemdetails":[{"BoundId":"Value2","isexpired":true,"FamilyCode":"PREMIUM","availabilityDetails":[{"travelID":"AAA-AB1234-AAABBB-2022-11-10-1111","quota":"X","scale":"XXX","class":"X"}]}]}]},"warnings":[{"code":"xxxx","detail":"xxxxxxxx","title":"xxxxxxxx"}]}')
.data.RenewalDetails[0].Itemdetails.find { itemDetail ->
itemDetail.availabilityDetails[0].travelID.length() == 33
}?.BoundId
println "Hello " + BoundId
Something like this:
def txt = '''\
{
"data": {
"RenewalDetails": [
{
"ExpiryDetails": {
"duration": "xxxxx",
"destination": "LHR",
"from": "AUH",
"value": 2,
"segments": [
{
"valudeid": "xxx-xx6262-xxxyyy-1111-11-11-1111"
}
]
},
"Itemdetails": [
{
"BoundId": "Value1",
"isexpired": true,
"FamilyCode": "PREMIUM",
"availabilityDetails": [
{
"travelID": "AAA-AB1234-AAABBB-2022-11-10-1111",
"quota": "X",
"scale": "XXX",
"class": "X"
}
]
}
]
},
{
"ExpiryDetails": {
"duration": "xxxxx",
"destination": "LHR",
"from": "AUH",
"value": 2,
"segments": [
{
"valudeid": "xxx-xx6262-xxxyyy-1111-11-11-1111"
}
]
},
"Itemdetails": [
{
"BoundId": "Value2",
"isexpired": true,
"FamilyCode": "PREMIUM",
"availabilityDetails": [
{
"travelID": "AAA-AB1234-AAABBB-2022-11-10-1111",
"quota": "X",
"scale": "XXX",
"class": "X"
}
]
}
]
}
]
},
"warnings": [
{
"code": "xxxx",
"detail": "xxxxxxxx",
"title": "xxxxxxxx"
}
]
}'''
def json = new groovy.json.JsonSlurper().parseText txt
List<String> BoundIds = json.data.RenewalDetails.Itemdetails*.find { itemDetail ->
itemDetail.availabilityDetails[0].travelID.size() == 33 && itemDetail.FamilyCode == 'PREMIUM'
}?.BoundId
assert BoundIds.toString() == '[Value1, Value2]'
Note, that you will get the BoundIds as a List
If you amend your code like this:
def json = new groovy.json.JsonSlurper().parse(prev.getResponseData()
you would be able to access the number of returned items as:
def size = json.data.RenewalDetails.size()
as RenewalDetails represents a List
Just add as many queries you want using Groovy's && operator:
find { itemDetail ->
itemDetail.availabilityDetails[0].travelID.length() == 33 &&
itemDetail.FamilyCode.equals('PREMIUM')
}
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?

Karate API framework - How to assert the empty value of a key and if that value is empty then assert that some other key should not present

Is there any way in Karate through which I can check that if any value is coming as empty string then some other key in the response should not present -
For example if you see below sample json response one of the results[*].source.Descriptions[*].text is empty and at the same node the preview results[*].source.preview is not present
So any straight forward solution in karate which can check that if Descriptions.text is '' then preview should not be present at that node
{
"total": 10,
"count": 10,
"results": [
{
"id": "1",
"source": {
"type": "general",
"Description": [
{
"text": ""
}
]
}
},
{
"id": "2",
"source": {
"type": "general",
"preview": "Your name",
"Description": [
{
"text": "Your name is Karate"
}
]
}
}
]
}
Here you go. Read the docs in case anything is not clear:
* def isValid = function(x){ var desc = x.source.Description[0].text; return desc === '' ? !x.preview : true }
* match each response.results == '#? isValid(_)'

how to parse the json file and read the json elements in groovy

Hi i am trying to parse the below json file. I tried using jsonsluper and parsed the file. I executed below command. Nothing works.
def test =newjsonslurper().parsetext(organist)
test.resources.each{
println it.resources.metadata. "guid"
println it.resources.entity. "name"
}
This is the json file format
resources: [
{
"metadata" :{
"guid":"cya"
"url": "dummy.test"
},
"entity" :
{
"name": "system"
"status": "active"
}
}
{
"metadata" :
{
"guid":"cya"
"url": "dummy.test"
},
"entity" :
{
"name": "system"
"status": "active"
}
}
]
There were a couple of problems:
JsonSlurper().parseText() expects a String. If you're wanting to parse a file, use something like def response = new JsonSlurper().parse(new File('JsonFile.json'))
The JSON payload is not valid: it's missing a few brackets and commas.
The following code should work:
import groovy.json.JsonSlurper
def test = new JsonSlurper().parseText '''
{"resources": [
{
"metadata": {
"guid": "cya",
"url": "dummy.test"
},
"entity": {
"name": "system",
"status": "active"
}
},
{
"metadata": {
"guid": "cya",
"url": "dummy.test"
},
"entity": {
"name": "system",
"status": "active"
}
}
]}
'''
test.resources.each {
println it.metadata.guid
println it.entity.name
}

Rest assured, using Gpath query gives an error "The parameter "..." was used but not defined. Define parameters using the JsonPath.params(...)"

I'm new to rest-assured and I'm currently spiking it in order to implement it in our testing framework.
The problem I'm facing is to extract an object from a Json array from the REST response.
The example json I'm using:
{
"MRData": {
"xmlns": "http://ergast.com/mrd/1.4",
"series": "f1",
"url": "http://ergast.com/api/f1/2016/drivers.json",
"limit": "30",
"offset": "0",
"total": "24",
"DriverTable": {
"season": "2016",
"Drivers": [
{
"driverId": "alonso",
"permanentNumber": "14",
"code": "ALO",
"url": "http://en.wikipedia.org/wiki/Fernando_Alonso",
"givenName": "Fernando",
"familyName": "Alonso",
"dateOfBirth": "1981-07-29",
"nationality": "Spanish"
},
{
"driverId": "bottas",
"permanentNumber": "77",
"code": "BOT",
"url": "http://en.wikipedia.org/wiki/Valtteri_Bottas",
"givenName": "Valtteri",
"familyName": "Bottas",
"dateOfBirth": "1989-08-28",
"nationality": "Finnish"
}
]
}
}
}
Things i have tried so far:
This assertion is working
RestAssured.rootPath = "MRData.DriverTable.Drivers";
given()
.when()
.get("http://ergast.com/api/f1/2016/drivers.json")
.then()
.assertThat()
.body("find { find { d -> d.driverId == 'alonso' }.code }.code", equalTo("ALO"));
But I'm trying to actually get the Json of the particular array item
RestAssured.rootPath = "MRData.DriverTable.Drivers";
given()
.when()
.get("http://ergast.com/api/f1/2016/drivers.json")
.then()
.extract()
//.jsonPath().param("driverId", "alonso").get("find { d -> d.driverId == driverId }");
.path("find { d -> d.driverId == 'alonso' }");
Tried with both ways (one is commented out). But I get an error :
"The parameter "driverId" was used but not defined. Define parameters using the JsonPath.params(...)"
RestAssured.rootPath = "MRData.DriverTable.Drivers"; works only for body expectations. For extraction you have to use full path to paramter e.g. MRData.DriverTable.Drivers.find { it.#driverId == 'alonso' }

Search JSON for multiple values, not using a library

I'd like to be able to search the following JSON object for objects containing the key 'location' then get in return an array or json object with the 'name' of the person plus the value of location for that person.
Sample return:
var matchesFound = [{Tom Brady, New York}, {Donald Steven,Los Angeles}];
var fbData0 = {
"data": [
{
"id": "X999_Y999",
"location": "New York",
"from": {
"name": "Tom Brady", "id": "X12"
},
"message": "Looking forward to 2010!",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X999/posts/Y999"
},
{
"name": "Like",
"link": "http://www.facebook.com/X999/posts/Y999"
}
],
"type": "status",
"created_time": "2010-08-02T21:27:44+0000",
"updated_time": "2010-08-02T21:27:44+0000"
},
{
"id": "X998_Y998",
"location": "Los Angeles",
"from": {
"name": "Donald Steven", "id": "X18"
},
"message": "Where's my contract?",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X998/posts/Y998"
},
{
"name": "Like",
"link": "http://www.facebook.com/X998/posts/Y998"
}
],
"type": "status",
"created_time": "2010-08-02T21:27:44+0000",
"updated_time": "2010-08-02T21:27:44+0000"
}
]
};
#vsiege - you can use this javascript lib (http://www.defiantjs.com/) to search your JSON structure.
var fbData0 = {
...
},
res = JSON.search( fbData0, '//*[./location and ./from/name]' ),
str = '';
for (var i=0; i<res.length; i++) {
str += res[i].location +': '+ res[i].from.name +'<br/>';
}
document.getElementById('output').innerHTML = str;
Here is a working fiddle;
http://jsfiddle.net/hbi99/XhRLP/
DefiantJS extends the global object JSON with the method "search" and makes it possible to query JSON with XPath expressions (XPath is standardised query language). The method returns an array with the matches (empty array if none were found).
You can test XPath expressions by pasting your JSON here:
http://www.defiantjs.com/#xpath_evaluator