首页 > 解决方案 > 将结果保存到新的 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,versionedRepresentations",
         "id": "217579",
         "self": "issue/217579",
         "key": "ART-4069",
         "fields": {"summary": "Verification \\"C\\""}
      },
            {
         "expand": "operations,versionedRepresentations",
         "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 })
}

结果:
key;summary
ART-4070;#[ART] Pre.3 验证 "S"
ART-4069;验证 "C"
ART-4068;#[ART] 枚举类型

标签: jsongroovyexport-to-csv

解决方案


要使用当前代码,您可以使用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")


推荐阅读