0

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
        }
      ]
    }
  }
p_nair
  • 57
  • 1
  • 1
  • 5

1 Answers1

0

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 }])
        ]}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 15 '23 at 00:08