将json转换为CSV文件的Groovy代码
有人有任何示例Groovy代码来将JSON文档转换为CSV文件吗?我曾尝试在谷歌上搜索,但没有结果 示例输入(来自注释): 有关编辑的详细信息:将json转换为CSV文件的Groovy代码,groovy,Groovy,有人有任何示例Groovy代码来将JSON文档转换为CSV文件吗?我曾尝试在谷歌上搜索,但没有结果 示例输入(来自注释): 有关编辑的详细信息: def export(){ def exportCsv = [ [ id:'1', color:'red', planet:'mars', description:'Mars, the "red" planet'], [ id:'2', color:'green', planet:'neptune',
def export(){
def exportCsv = [ [ id:'1', color:'red', planet:'mars', description:'Mars, the "red" planet'],
[ id:'2', color:'green', planet:'neptune', description:'Neptune, the "green" planet'],
[ id:'3', color:'blue', planet:'earth', description:'Earth, the "blue" planet'],
]
def out = new File('/home/mandeep/groovy/workspace/FirstGroovyProject/src/test.csv')
exportCsv.each {
def row = [it.id, it.color, it.planet,it.description]
out.append row.join(',')
out.append '\n'
}
return out
}
好的,这个怎么样:
import groovy.json.*
// Added extra fields and types for testing
def js = '''{"infile": [{"field1": 11,"field2": 12, "field3": 13},
{"field1": 21, "field4": "dave","field3": 23},
{"field1": 31,"field2": 32, "field3": 33}]}'''
def data = new JsonSlurper().parseText( js )
def columns = data.infile*.keySet().flatten().unique()
// Wrap strings in double quotes, and remove nulls
def encode = { e -> e == null ? '' : e instanceof String ? /"$e"/ : "$e" }
// Print all the column names
println columns.collect { c -> encode( c ) }.join( ',' )
// Then create all the rows
println data.infile.collect { row ->
// A row at a time
columns.collect { colName -> encode( row[ colName ] ) }.join( ',' )
}.join( '\n' )
上面印着:
"field3","field2","field1","field4"
13,12,11,
23,,21,"dave"
33,32,31,
这在我看来是正确的这将根据您的json定制,因为没有规定json数组中的对象必须包含相同的属性。你有一些json的例子吗?你试过什么?你有什么困难?我有字符串JSON数据。我想使用groovy代码将这个json数据转换为csv文件。像这里一样,我已经用静态数据创建了csv文件,但我想从字符串json对象创建csv文件,并想使用Groovy中的发送电子邮件代码将此csv文件作为附件发送。您的问题很明显,您有一些json,并且想创建csv,但您有什么json?任何解决方案都是您的json所独有的,因为json可以采用多种形式,并且不必很容易地匹配csv格式。您能否将一些Json示例作为编辑发布到您的问题中?具有以下结构(表示为Json)的地图:[公司id:'1'网址:'',电话:'+44 11111',传真:'',电子邮件:'',地址:[[键入:“办公室”,街道地址:“沃达丰之家,连接”,邮政编码:“RG14 2FN”,地理:[lat:51.4145,lng:1.318385]],雇员人数:91272,naics:[主要:[“517210”:“无线电信运营商(卫星除外)”,],次要:[“517110”:“有线电信运营商”,“517919”:“互联网服务提供商”,“518210”:“网络托管”]],我认为您应该补充您的问题,而不是使用注释…您可以编辑您的问题…如果值包含双引号,脚本将失败,必须使用两个双引号对其进行转义,例如
da“ve
应产生“da”“ve”
。是的…您应该使用CSV库而不是上述库
"field3","field2","field1","field4"
13,12,11,
23,,21,"dave"
33,32,31,