Groovy从地图和子地图收集 [英] Groovy collect from map and submap
问题描述
我需要将JSON响应转换为csv文件.我可以从这里成功使用Tim Yates的出色代码: Groovy代码将json转换为CSV文件
I had a requirement to convert a JSON response into a csv file. I was able to successfully use Tim Yates' excellent code from here: Groovy code to convert json to CSV file
我现在还需要在csv中包括JSON的嵌套子图.地图和子地图之间的关系是1:1.
I now need to include the JSON's nested submap in the csv as well. The relationship between the map and submap is 1:1.
我一直无法为collect语句获得正确的语法,该语句将检索已解析的地图和子地图的键/值.
I've been unable to get the correct syntax for a collect statement that will retrieve both the parsed map and submap key/values.
示例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,以轻松收集每个键/值:
I would like to either 1) Convert the JSON as follows to collect each key/value easily:
...
{
created_at=2019-03-27
, entity_id=2
, employee_id=Emp1
, employee_type=CSR
}
...
或2)找出是否可以使用Groovy的collect方法将地图/子地图检索为平面地图.
or 2) Find out if there's a way to use Groovy's collect method to retrieve the map/submap as a flat map.
很不幸,我不是一名程序员,任何帮助将不胜感激!
I am unfortunately not a programmer by trade, and any help would be appreciated!
推荐答案
以下是flatten
闭包,该闭包以递归方式展平了一个项目:
Here is the flatten
closure which flattens an item recursively:
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)
,这样看起来就像这样:
You should just replace row
with flatten(row)
at your last line so it looks like this:
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"
这篇关于Groovy从地图和子地图收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!