Home > database >  How to transform complex json structure using Groovy?
How to transform complex json structure using Groovy?

Time:08-25

first of all, thanks for your time!

So i've been using Groovy for a couple of weeks now but i can't seems to be able to transform the following json structure:

{
  "collection_1": [
    [
      "value_1",
      "value_2",
      "value_3"
    ],
    [
      "value_1",
      "value_2",
      "value_3",
      "value_4"
    ]
  ],
  "collection_2": [
    [
      "value_1",
      "value_2",
      "value_3",
      "value_4",
      "value_5"
    ]
  ],
  "collection_3": [
    [
      "value_1",
      "value_2"
    ]
  ]
}

To something like:

{
  "collection_1": [
    [
      "value_1": false,
      "value_2": false,
      "value_3": false
    ],
    [
      "value_1": false,
      "value_2": false,
      ...

Here is how i did it:

Map<String, Object> getSelectableItems(Map<String, Object> jsonDeserialized) {
  def selectableItems = [:]

  jsonDeserialized.each { collection, subCollection ->
   selectableItems.put(collection, [:])
   subCollection.eachWithIndex { items, index ->
    selectableItems.get(collection).putAt(index, items.collect { value ->
     [
       "${value}" : false
     ]
    })
   }
  }

  return selectableItems
}
​

I've been trying for days, it isn't that hard, i even succeed but the final code is looking terribly wrong. Do you have any idea of how I could achieve something like so with the power of Groovy?

Thanks groovy pros :D

CodePudding user response:

import groovy.json.*

def data = new JsonSlurper().parseText('''
  {...your json here...}
''')

data.replaceAll { k, v -> v = v.collect { it.collectEntries { [it,false] } } }


println new JsonBuilder(data).toPrettyString()

output:

{
    "collection_1": [
        {
            "value_1": false,
            "value_2": false,
            "value_3": false
        },
        {
            "value_1": false,
            "value_2": false,
            "value_3": false,
            "value_4": false
        }
    ],
    "collection_2": [
        {
            "value_1": false,
            "value_2": false,
            "value_3": false,
            "value_4": false,
            "value_5": false
        }
    ],
    "collection_3": [
        {
            "value_1": false,
            "value_2": false
        }
    ]
}
  • Related