Reputation: 3728
JSON File
{
"FormElements": [
{
"ButtonLabel": [
"New",
"Done",
"Save as draft",
"Submit",
"Next",
"Finish"
],
"XPath": "//*[text()='LABEL']"
}
]
}
From the above JSON to find a particular item in the array. For example, I want to Find "New" from the above one. Below is my code but its return null
def isAvailable = InputJSON.FormElements.find {it."ButtonLabel[0]"=="New" }
Can anyone validate the above code, whether any changes are required in this?
Upvotes: 0
Views: 2596
Reputation: 20699
From your code follows that you want to check for existence of an element, rather than find that element.
With this im mind the code can look like:
import groovy.json.*
def json = new JsonSlurper().parseText '''{ "FormElements": [ {"ButtonLabel": [ "New", "Done", "Save as draft", "Submit", "Next", "Finish"], "XPath": "//*[text()='LABEL']" } ] }'''
boolean isAvailable = 'New' in json.FormElements*.ButtonLabel.flatten()
boolean isNotAvailable = 'AAAAA' in json.FormElements*.ButtonLabel.flatten()
assert isAvailable && !isNotAvailable
Upvotes: 1
Reputation: 107
Normally I would use indexOf.
InputJson.FormElements[0].ButtonLabel.indexOf('New')
-1 means its not present. Its hard to tell not knowing the source of your json... etc
Upvotes: 0
Reputation: 4572
Slight syntax error accessing ButtonLabel
items. It should be,
def isAvailable = InputJSON.FormElements.find {it."ButtonLabel".[0]=="New" }
OR
def isAvailable = InputJSON.FormElements.find {it."ButtonLabel".get(0) == "New" }
Upvotes: 0