Groovy从地图和子地图收集

时间:2019-03-27 22:25:51

标签: json csv groovy nested

我需要将JSON响应转换为csv文件。我可以从这里成功使用蒂姆·耶茨的出色代码:Groovy code to convert json to CSV file

我现在还需要在csv中包括JSON的嵌套子图。地图和子地图之间的关系是1:1。

我一直无法为collect语句获得正确的语法,该语句将检索已解析的地图和子地图的键/值。

示例JSON

{items=
[
{ 
  created_at=2019-03-27
, entity_id=1
, extension_attributes=[]
},

{
  created_at=2019-03-27
, entity_id=2
, extension_attributes= { employee_id=Emp1, employee_type=CSR}//nested submap
}
]}

时髦

import groovy.json.*

def data = new JsonSlurper().parseText( json ); //"json" is from GET request

def columns = ["created_at","entity_id","employee_id","employee_type"]

def encode = { e -> e ? /"$e"/ : "$e"}

requestFile.append( columns.collect { c -> encode( c ) }.join( ',' ) + '\n');

requestFile.append( data.items.collect { row ->columns.collect { colName -> encode( row[ colName ] ).replaceAll("null","") }.join( ',' )}.join( '\n' ) );//unsure how to use data.items.collect to fetch submap

我想 1)如下转换JSON,以轻松收集每个键/值:

...
{
  created_at=2019-03-27
, entity_id=2
, employee_id=Emp1
, employee_type=CSR
}
...

或2)找出是否可以使用Groovy的collect方法将地图/子地图检索为平面地图。

很不幸,我不是一名程序员,任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

这里是flatten闭包,它以递归方式展平一个项目:

def flatten
flatten = { row ->
    def flattened = [:]
    row.each { k, v ->
        if (v instanceof Map) {
            flattened << flatten(v)
        } else {
            flattened[k] = v
        }
    }
    flattened
}

您应该在最后一行将row替换为flatten(row),如下所示:

requestFile.append(data.items.collect { row ->
    columns.collect {
        colName -> encode(flatten(row)[colName]).replaceAll("null", "")
    }.join(',')
}.join('\n'))

结果如下:

"created_at","entity_id","employee_id","employee_type"

"2019-03-27","1",,
"2019-03-27","2","Emp1","CSR"

答案 1 :(得分:0)

还发现以下内容允许使用collect方法来获取嵌套元素:

def m = data.items.collect{[/"${it?.created_at?:''}"/,/"${it?.extension_attributes?.entity_id?:''}"/,/"${it?.extension_attributes?.employee_id?:''}"/,/"${it?.extension_attributes?.employee_type?:''}"/]}

m.each{requestFile.append(it.join(',')+'\n')}