Prabu
Prabu

Reputation: 3728

Groovy: find a particular item from JSON array

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

Answers (3)

injecteer
injecteer

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

SuperSpamTube
SuperSpamTube

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

aldrin
aldrin

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

Related Questions