0

尝试读取和转换输入文件具有的 JSON 文件:

{
  "id": “A9”,
  "roles": [
  {"title": “A”, “type”: “alpha” },
  {"title": “B”, “type”: “beta” },
  ]
},

{
  "id": “A10”,
  "roles": [
  {"title": “D”, “type”: “delta” },
  ]
}, 

但是需要对期望值处于同一级别的库进行转换:

{
  "roles": [
  {"id": “A9”, "title": “A”, “type”: “alpha” },
  {"id": “A9”, "title": “B”, “type”: “beta” },
  ]
},

{
  "roles": [
  {"id": “A10”, "title": “D”, “type”: “delta” },
  ]
}, 

我可以使用 JsonSlurper 读取输入,但坚持如何对其进行非规范化。

4

1 回答 1

1

有了这个data.json(注意我必须清理尾随逗号,因为 Groovy 的 JSON 解析器不会接受它们):

{
  "records":[{
    "id": "A9",
    "roles": [
      {"title": "A", "type": "alpha" },
      {"title": "B", "type": "beta" }
    ]
  },
  {
    "id": "A10",
    "roles": [
      {"title": "D", "type": "delta" }
    ]
  }]
}

你可以这样做:

def parsed = new groovy.json.JsonSlurper().parse(new File("data.json"))
def records = parsed.records
records.each { record ->
  record.roles.each { role ->
    role.id = record.id
  }
  record.remove('id')
}
于 2017-05-07T22:16:43.357 回答