使用JsonSlurper展平JSON读取

时间:2017-05-07 21:10:18

标签: groovy jsonslurper

尝试读取和转换输入文件所在的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读取输入,但仍坚持如何反规范化。

1 个答案:

答案 0 :(得分: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')
}