Groovy JSON转换为CSV

问题描述

我在使用Groovy解析JsonSlurper的Json时遇到问题。你能帮忙吗? 我的示例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,"id": "217579","self": "issue/217579","key": "ART-4069","fields": {"summary": "Verification \"C\""}
      },"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

当我尝试在代码开头解析此json时,出现错误: 线程“ main” groovy.json.JsonException中的异常:预期为“}”或“,”,但当前字符为“ S”,其int值为83

当前读取的字符为'S',int值为83 预期为'}'或',',但当前字符为'S',其int值为83 行号13 索引编号321 “ fields”:{“ summary”:“#[ART] Pre.3验证” S“”}

代码

import groovy.json.*

def jsonSlurper = new JsonSlurper()
def json = '''
{
   "expand": "schema,]
}
'''
def obj = jsonSlurper.parseText(json)
println obj

请帮助

解决方法

首先:您需要在\\字符串内加双''';第二个是, 在列表的最后一个元素上。

import groovy.json.JsonSlurper

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,"id": "217579","self": "issue/217579","key": "ART-4069","fields": {"summary": "Verification \\"C\\""}
      },"id": "217577","self": "issue/217577","key": "ART-4068","fields": {"summary": "#[ART] Enum type"}
      }
   ]
}
'''
def obj = jsonSlurper.parseText(json)
println obj