1

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

2
  • Please update your question with your code so that we can help you. Commented Aug 23, 2022 at 14:42
  • Done, sorry I simply wanted a hint not a fully working solution Commented Aug 23, 2022 at 14:51

1 Answer 1

3
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
        }
    ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, it's a lot better! awesome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.