json - 将结果保存到新的 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] 枚举类型
解决方案
要使用当前代码,您可以使用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")
推荐阅读
- javascript - 验证用户是否存在或不使用 nodejs
- javascript - 如何绘制 geoAlbersUsa() 投影的经纬度坐标?
- c# - 这个依赖注入 (DI) 服务在注册为瞬态时如何维护数据?
- python - 如何避免 div 在使用 Python/Selenium 抓取动态生成的网站时清空自己?
- flutter - Visual Studio Code Flutter 无法更新 Dart SDK
- html - 当页面在文档片段处重新加载时,Bootstrap 5 Scrollspy 设置了不正确的活动部分
- google-sheets - 添加基于年份的动态下拉列表以更改 Google 表格查询的结果
- c# - 多少内存使用字节枚举,这是否优化了 C# 中的内存/速度?
- python - 使用 Python 将 pdf 数据转换为 JSON 格式?
- javascript - 使用 Axios 和 Pipe Function 执行 POST 方法