Groovy模板图

时间:2019-01-14 15:08:52

标签: dictionary groovy

我正在尝试构建一个读取json文件的groovy脚本

"Std": { "isAbstract": true, "jdk": "8", "mvn": "3.5.4" },  
"StdInstall": { "isAbstract": true, "inherits": ["Std"], "mvnCmd": "clean install" }, 
"StdDeploy": { "isAbstract": true, "inherits": ["Std"], "mvnCmd": "clean deploy" }, 
"WDF2": { "isAbstract": true, "svn": "http://..." },
"WDF2_install": { "inherits": ["WDF2", "StdInstall"] },
"WDF2_deploy": { "inherits": ["WDF2", "StdDeploy"] }

并尝试创建一个新映射,用sam映射中的正确值替换所有继承键 例如json在输出中看起来像这样

"Std": { "isAbstract": true, "jdk": "8", "mvn": "3.5.4" },
"StdInstall": { "isAbstract": true, "jdk": "8", "mvn": "3.5.4", "mvnCmd": "clean install" },
"StdDeploy": { "isAbstract": true, "jdk": "8", "mvn": "3.5.4", "mvnCmd": "clean deploy" },  
"WDF2": { "isAbstract": true, "svn": "http://..." }, 
"WDF2_install": { "isAbstract": true, "svn": "http://...", "jdk": "8", "mvn": "3.5.4", "mvnCmd": "clean install" },

"WDF2_deploy": { "isAbstract": true, "svn": "http://...", "jdk": "8", "mvn": "3.5.4", "mvnCmd": "clean deploy" }

从而用同一张图中的正确值替换所有继承键,并删除重复项。

我想出了第一部分代码,但无法继续进行操作

def result = new LinkedHashMap(temp)

temp.each{ k, v ->
v.each{
k1,v1 -> 
if(k1 == "inherits" ){ 
    v1.each{ val->
    val = temp[val]
    println k

    def new1= v+val
    println new1
      //result = v+temp[v2] 
      //println result
    } 


} 
} 
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我确信其他人会找到更好的解决方案,但是到目前为止,我想到了这一点:

def result = temp.collectEntries {k,v ->
  if (v instanceof Map) {
    v = new HashMap(v)
    (v.remove("inherits")?:[]).each {ref -> v << temp[ref]}
  }
  [(k):v]

}

无论如何,我还是无法摆脱instanceof .....基本思想是json读入Map中的结果(如果您使用Groovy JSON,肯定是这种情况)。 collectEntries将通过为每个条目或地图条目提供地图来从旧地图中创建一个新地图。我选择了地图。 v << temp [ref]会将在temp [ref]下找到的映射的所有条目添加到v。v.remove(“ inherits”)删除继承条目,但也为我提供了该映射之前具有的值。 v.remove(“ inherits”)?:[]确保即使条目不存在,我也总是得到一个非空列表。如果存在,则使用“每个”展开地图,如果不存在,则什么也不会发生。最后,我用[[k]:v]构建了一个新的“局部地图”,该地图的key值为k,局部部分的值为v。 [k:v]会创建一个名为k的地图。

当然,如果需要,可以很容易地将其扩展为递归工作:

def replacer
replacer = {k,v ->
  if (v instanceof Map) {
    v = new HashMap(v)
    (v.remove("inherits")?:[]).each {ref -> v << temp[ref]}
    v = v.collectEntries replacer
  }
  [(k):v]
}
def result = temp.collectEntries replacer

编辑:由于评论已更正版本:

def result = temp.collectEntries {k,v ->   
  if (v instanceof Map) {
    v = new HashMap(v)
    def inherits = []
    while (true) {
      inherits +=  v.remove("inherits")?:[]
      if (!inherits) break
      v << temp[inherits.pop()]
    }
  }
  [(k):v] 
} 

使用Groovy 3,您还可以同时使用...