2017-03-05 635 views
1

我只是两天岁,需要解析具有以下结构的json文件。我实际的想法是,我需要运行一组基于不同的顺序不同环境的工作,所以我想出了JSON作为输入文件的格式,以我的常规使用groovy脚本解析JSON(使用JsonSlurper)

{ 
    "services": [{ 
     "UI-Service": [{ 
      "file-location": "/in/my/server/location", 
      "script-names": "daily-batch,weekly-batch,bi-weekly-batch", 
      "seq1": "daily-batch,weekly-batch", 
      "seq2": "daily-batch,weekly-batch,bi-weekly-batch", 
      "DEST-ENVT_seq1": ["DEV1", "DEV2", "QA1", "QA2"], 
      "DEST-ENVT_seq2": ["DEV3", "DEV4", "QA3", "QA4"] 
     }] 
    }, { 
     "Mobile-Service": [{ 
      "file-location": "/in/my/server/location", 
      "script-names": "daily-batch,weekly-batch,bi-weekly-batch", 
      "seq1": "daily-batch,weekly-batch", 
      "seq2": "daily-batch,weekly-batch,bi-weekly-batch", 
      "DEST-ENVT_seq1": ["DEV1", "DEV2", "QA1", "QA2"], 
      "DEST-ENVT_seq2": ["DEV3", "DEV4", "QA3", "QA4"] 
     }] 
    }] 
} 

我尝试以下脚本解析JSON

 def jsonSlurper = new JsonSlurper() 
     //def reader = new BufferedReader(new InputStreamReader(new FileInputStream("in/my/location/config.json"),"UTF-8")) 
     //def data = jsonSlurper.parse(reader) 
     File file = new File("in/my/location/config.json") 
     def data = jsonSlurper.parse(file) 

     try{ 
      Map jsonResult = (Map) data; 
      Map compService = (Map) jsonResult.get("services"); 
      String name = (String) compService.get("UI-Service"); 
      assert name.equals("file-location"); 

     }catch (E){ 
      println Exception 
     } 

我需要首先读所有服务(UI服务,移动设备服务,等等。)然后它们的元素和它们的用于从对象JsonParser读取值

回答

2

实施例:

def data = jsonSlurper.parse(file) 
data.services.each{ 
    def serviceName = it.keySet() 
    println "**** key:${serviceName} ******" 
    it.each{ k, v -> 
     println "element name: ${k}, element value: ${v}" 
    } 
} 

其他选项:

println data.services[0].get("UI-Service")["file-location"] 
println data.services[1].get("Mobile-Service").seq1 
3

或者你可以这样做:

new JsonSlurper().parseText(jsonTxt).services*.each { serviceName, elements -> 
    println serviceName 
    elements*.each { name, value -> 
     println " $name = $value" 
    } 
} 

但是这取决于你想要什么(你不会真的在这个问题解释)

+0

基于我需要检索数据,#1 - 需要找到属于哪个DEST-ENVT_seq组(例如:DEST-ENVT_seq2),并且从用户获得只有envt名称(例如:DEV2或QA3)然后根据我需要fi的组名nd seq(例如:seq2)并从文件位置复制这些文件并执行 – Mowgli