簡體   English   中英

在 Groovy 中將 JSON 解析為 CSV

[英]Parsing JSON to CSV in Groovy

我正在嘗試將 json 文件解析為 csv。 你能幫忙嗎? 示例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"}
      }
   ]
}

結果 csv 應該是這樣的:

key;summary
ART-4070;#[ART] Pre.3 Verification \"S\"
ART-4069;Verification \"C\"
ART-4068;#[ART] Enum type

我試過這樣的代碼:

import groovy.json.*

def jsonSlurper = new JsonSlurper()
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"}
      }
   ]
}
'''
def obj = jsonSlurper.parse(json)

def columns = obj.issues*.keySet().flatten().unique()

// remove nulls
def encode = { e -> e == null ? '' : e  }

// Print all the column names
println columns.collect { c -> encode( c ) }.join( ';' )

// create all the rows
println obj.issues.collect { row ->
    // A row at a time
    columns.collect { colName -> encode( row[ colName ] ) }.join( ';' )
}.join( '\n' )

但結果是錯誤的:

expand;id;self;key;fields operations,versionedRepresentations;217580;issue/217580;ART-4070;[summary:#[ART] Pre.3 Verification "S"] 操作,versionedRepresentations;217579;issue/217579;ART- 4069;[摘要:驗證“C”]操作,版本化表示;217577;問題/217577;ART-4068;[摘要:#[ART]枚舉類型]

我怎樣才能從 json 文件中只提取我想要的內容? 我只需要兩列:它們的鍵、摘要和值。

您只想從問題列表中提取特定信息,並且需要不同的策略來提取這些信息。 所以我會使用“配置”來描述提取(參見下面的地圖config )。 然后代碼與您的原始代碼非常接近(提取了一些常用代碼等)

import groovy.json.*

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(";"))
}

// main
def obj = new JsonSlurper().parse("data.json" as File)
csvLine(config.keySet())
obj.issues.each{ issue ->
    csvLine(config.values().collect{ f -> f issue })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM