在JSON数组中搜索数据并在grails中的数组列表中输入

时间:2016-07-13 07:09:47

标签: arrays json grails groovy

我有一个像[gender, axonVoucherCode]的列表 我还有一个Json数组[[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 ?]]

我想创建一个列表,其中包含第一个列表的相应值,如[Gender?,Axon Voucher Code ?]。我使用JsonSlurper解析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

这是我的JSON文件格式。

  {"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 ?"}
]}

请帮我解决这个问题。谢谢

1 个答案:

答案 0 :(得分:1)

假设我理解你的问题,这应该有效:

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')

此处listOfValues将等于['Date and time of ED visit?', 'Axon Voucher Code ?']