0

Trying to read and transform a JSON file where the input file has:

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

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

But requires transformation for a library which expects values at the same level :

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

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

I'm able to read the input with JsonSlurper, but stuck on how to denormalize it.

Brad Schoening
  • 1,281
  • 6
  • 22

1 Answers1

1

With this data.json (notice I had to clean up trailing commas as Groovy's JSON parser will not accept them):

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

You can do it this way:

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')
}
Hugues M.
  • 19,846
  • 6
  • 37
  • 65