将 json 转换为 CSV 文件的 Groovy 代码

标签 groovy

有没有人有将 JSON 文档转换为 CSV 文件的示例 Groovy 代码?我曾尝试在 Google 上进行搜索,但无济于事。

示例输入(来自评论):

[ company_id: '1',
  web_address: 'vodafone.com/',
  phone: '+44 11111',
  fax: '',
  email: '',
  addresses: [ 
      [ type: "office", 
        street_address: "Vodafone House, The Connection",
        zip_code: "RG14 2FN",
        geo: [ lat: 51.4145, lng: 1.318385 ] ]
  ],
  number_of_employees: 91272,
  naics: [
      primary: [ 
          "517210": "Wireless Telecommunications Carriers (except Satellite)" ],
      secondary: [ 
          "517110": "Wired Telecommunications Carriers",
          "517919": "Internet Service Providers",
          "518210": "Web Hosting"
      ]
  ]

来自编辑的更多信息:

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 转换为 CSV 文件的 Groovy 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21576162/

相关文章:

java - 使用带有 Grails 后端的 jQuery 的进度条?

grails - 将简单的grails(1.3.7)WAR文件部署到JBoss 7.0.1

unit-testing - Groovy Spock 文件测试

java - Groovy - 编写和格式化 excel 2010

grails - 常规/Grails : How to compose closures without breaking DSL

Grails 中的 jquery TreeView

java - ElasticSearch Java API 的异步特性

http - 我在使用 wget 时收到 cookie,但在使用 groovy 脚本时没有收到 cookie

mysql - 计算数据集之间相似度百分比的有效方法

grails - 编写单元测试以保存模型