Sayem
Sayem

Reputation: 713

Search data in JSON array And Put in in array list in grails

I have a list like [gender, axonVoucherCode] Also I have a Json Array [[gender:Gender?], [concussionHistory:History of previous concussion?], [previousConcussion:Number of previous concussions?], [historyMigraineChronic:History of migraine or chronic headaches?], [edTreatment:ED treatment ?], [axonVoucherCode:Axon Voucher Code ?]]

I want to make a list with corresponding value of 1st list like [Gender?,Axon Voucher Code ?] .I use JsonSlurper for parsing Json .

   def fetchQuestion(def list){
        def webRootDir = SCH.servletContext.getRealPath("/")
        def f = new File(webRootDir + "/jsons/" + "QuestionPart1")
        def questionList = new JsonSlurper().parseText(f.text)
        def newlists=[]
        println questionList.QuestionPart1
        questionList.QuestionPart1.each{
            println(it)
        }

        println(newlists);
      return newlists
    }
    //I want to put matching value to newlists

Here is my JSON file format .

  {"QuestionPart1":[
  {"gender":"Gender?"},
  {"concussionHistory":"History of previous concussion?"},
  {"previousConcussion":"Number of previous concussions?"},
  {"historyMigraineChronic":"History of migraine or chronic headaches?"},
  {"edvisitTime":"Date and time of ED visit?"},
  {"injuryTime":"Date and time of Injury?"},
  {"mechanismInjury":"Mechanism of Injury?"},
  {"sportsType":"Choose Sport?"},
  {"signAndSymptom":"Select the signs and symptoms the subject experienced following injury?"},
  {"durationLossConsciousness":"Duration of loss of Conciousness ? "},
  {"durationBeforeAmnesia":"Duration of Amnesia for events BEFORE injury ?"},
  {"durationAfterAmnesia":"Duration of Amnesia for events AFTER injury ?"},
  {"ctObtainedED":"Head CT obtained in ED ?"},
  {"edTreatment":"ED treatment ?"},
  {"axonVoucherCode":"Axon Voucher Code ?"}
]}

Please help me to solve this problem .Thanks

Upvotes: 1

Views: 161

Answers (1)

tim_yates
tim_yates

Reputation: 171084

Assuming I understand your question, this should work:

def fetchQuestion(String ...keys){
    def webRootDir = SCH.servletContext.getRealPath("/")
    def f = new File(webRootDir + "/jsons/" + "QuestionPart1")
    def questionList = new JsonSlurper().parseText(f.text)
    def newlists=[]
    println questionList.QuestionPart1
    questionList.QuestionPart1.findResults { it.find { k, v -> k in keys }?.value }
}

def listOfValues = fetchQuestion('edvisitTime', 'axonVoucherCode')

Here, listOfValues will equal ['Date and time of ED visit?', 'Axon Voucher Code ?']

Upvotes: 1

Related Questions