Creating dynamic JSON objects using groovy

93 Views Asked by At

I am trying to convert a JSON array into a JSON object, keys of the JSON object are dynamic in nature, please find the example below.

"Section" field in the source array is getting converted to key of object in target JSON

Source:

[
    {
        "a": 0,
        "section": 1.0
    },
    {
        "a": 1,
        "section": 1.0
    },
    {
        "a": 2,
        "section": 2.0
    },
    {
        "a": 3,
        "section": 2.0
    },
    {
        "a": 4,
        "section": 3.0
    }
]

Target:

{
    "1": {
      "total": 1,
      "data": [
        {
          "a": 0
        },
        {
          "a": 1
        }
      ]
    },
    "2": {
      "total": 5,
      "data": [
        {
          "a": 2
        },
        {
          "a": 3
        }
      ]
    },
    "3": {
      "total": 4,
      "data": [
        {
          "a": 4
        }
      ]
    }
  }
1

There are 1 best solutions below

1
Ksieniia Kyrychenko On

You can try this

def list = [
        [
                "a"      : 0,
                "section": 1.0
        ],
        [
                "a"      : 1,
                "section": 1.0
        ],
        [
                "a"      : 2,
                "section": 2.0
        ],
        [
                "a"      : 3,
                "section": 2.0
        ],
        [
                "a"      : 4,
                "section": 3.0
        ]
]
def modified = list.groupBy { it -> (it.section).intValue() }
        .collectEntries {[
                (it.key.toString()) : ([
                data: it.value.collect { it.findAll {it.key != 'section'}},
                total: it.value.sum { val -> val.a }])
        ]}