将结果保存到新的csv文件而不是println Groovy

问题描述

如何将Groovy脚本的结果保存到新文件? C:/temp/all1.csv。我想将json文件解析为csv,脚本运行正常,但我不知道如何将结果保存到新文件中。请帮忙。

import groovy.json.*
import java.io.File
def json ='''
{
   "expand": "schema,names","startAt": 0,"maxResults": 50,"total": 21,"issues":    [
            {
         "expand": "operations,versionedRepresentations","id": "217580","self": "issue/217580","key": "ART-4070","fields": {"summary": "#[ART] Pre.3 Verification \\"S\\""}
      },{
         "expand": "operations,"id": "217579","self": "issue/217579","key": "ART-4069","fields": {"summary": "Verification \\"C\\""}
      },"id": "217577","self": "issue/217577","key": "ART-4068","fields": {"summary": "#[ART] Enum type"}
      }
   ]
}
'''
File csvFile = new File( 'C:/temp/all1.csv')

def jsonSlurper = new JsonSlurper()
def config = [ // header -> extractor
    "key": { it.key },"summary": { it.fields.summary }
]

def encode(e) { // help with nulls; quote the separator
    (e ?: "").replaceAll(";","\\;")  
}

def csvLine(items) { // write items as "CSV"
  println(items.collect{ encode it }.join(";"))
}

def obj = new JsonSlurper().parseText(json)
csvLine(config.keySet())
obj.issues.each{ issue ->
    csvLine(config.values().collect{ f -> f issue })
}

结果:
键;摘要
ART-4070;#[ART] Pre.3验证字词“ S”
ART-4069;验证为“ C”
ART-4068;#[ART]枚举类型

解决方法

要使用当前代码,您可以在内部使用csvFile.append(...)而不是println csvLine功能,这可能取决于您的实际数据量 是性能和资源之间的良好折衷。

或者您可以一次写入整个CSV。例如

// prepare whole table
def data = [config.keySet()]
data.addAll(
    obj.issues.collect{ issue ->
        config.values().collect{ f -> f issue }
    }
)
// write table as csv
def csvFile = "/tmp/out.csv" as File
csvFile.text = data.collect{
    it.collect{ encode it }.join(";")9
}.join("\n")