doubtsreadyapi
5 years agoContributor
Require condition to check depending upon the Json Node response
Hi, Depending upon the json node, for a json node if the key exists and value exists i have to set property in custom properties and if the key value doesnt exist then i have to set the propert...
- 5 years ago
Hi,
Firstly, have you tried logging the response to see what you have?
def response_id = context.expand( '${CurrentSprint#Response#$[\'values\'][0][\'id\']}' ) log.info(response_id); if (response_id !=null)
XPath is more for XML response and not JSON. If you want to use XPath, then maybe pull the response as XML. E.g.
def response_id = context.expand( '${TestStepName#ResponseAsXml#$[\'values\'][0][\'id\']}' )
I haven't tested this by the way, but that should convert the response to XML so you can traverse with XPath.
Instead, you could convert the response to JSON using JSON Slurper and interrogate as a JSON Object....
import groovy.json.JsonSlurper; def slurper = new groovy.json.JsonSlurper(); // Obviously, you would need to pull the string from the response first. def result = slurper.parseText('{"maxResults" : 50,"startAt" : 0,"isLast" : false,"values" : [{"id" : 221,"startDate" : "2018-06-26T20:00:16.850Z","endDate" : "2018-07-09T21:00:00.000Z"}]}'); // Can we get ID? log.info(result.values.id); return result.values.id;
Re setting property value, I'd imagine that .testCases["Test"] is different from .testCases["TEST"]. Is your test case called 'Test' or 'TEST'.
Here's an example based on the JSON in your question on how to check and set Property Value if the id is there or not.
import groovy.json.JsonSlurper; def slurper = new groovy.json.JsonSlurper(); def result = slurper.parseText('{"maxResults" : 50,"startAt" : 0,"isLast" : false,"values" : [{"id":221, "startDate" : "2018-06-26T20:00:16.850Z","endDate" : "2018-07-09T21:00:00.000Z"}]}'); // Can we get ID? log.info(result.values[0].id); // Check for Id.... if (result.values[0].id){ def id = Integer.toString(result.values[0].id); testRunner.testCase.testSuite.testCases["Grab JSON - TestCase"].setPropertyValue("Active", "$id"); } else { testRunner.testCase.testSuite.testCases["Grab JSON - TestCase"].setPropertyValue("Active", "Not Found"); } return result;