William Pham
William Pham

Reputation: 291

Retrieve dynamic objects within JSON object and put to an array Groovy

I'm new to Groovy and couldn't find any resources related to this. I'm trying to extract data from a "dates" object and put it in an array of fixed objects within it. The reason for it is that the objects within dates will change and I'd like to put into fixed for easy manipulation:

Original:

{
"dates": {
    "2021-02-08": "8",
    "2021-02-09": "8",
    "2021-02-10": "8"
}}

Output wanted:

{
"dates": [
    {
    "date": "2021-02-08",
    "value": "8"
    },
    {
    "date": "2021-02-09",
    "value": "8"
    },
    {
    "date": "2021-02-10",
    "value": "8"
    },
]}

I'm trying to use the current codes:

arrayList = []
arrayList.add(content[0].dates)

It returns an [[2021-02-08:8, 2021-02-09:8, 2021-02-10:8]], but I cannot extract it as an array.

Any thoughts?

Upvotes: 0

Views: 316

Answers (2)

cfrick
cfrick

Reputation: 37073

You can turn a map into a list by collecting over it. E.g.

def json = """{"dates": { "2021-02-08": "8", "2021-02-09": "8", "2021-02-10": "8" }}"""
def data = new groovy.json.JsonSlurper().parseText(json)

def result = [dates: data.dates.collect{ k, v -> [date: k, value: v] }]

println result
// -> [dates:[[date:2021-02-08, value:8], [date:2021-02-09, value:8], [date:2021-02-10, value:8]]]

Upvotes: 2

William Pham
William Pham

Reputation: 291

I have found the solution in case someone will need it. Here's a pice of code which you can test on groovy console:

import groovy.json.JsonSlurper;
import groovy.json.JsonOutput;

def jsonSlurper = new JsonSlurper()
def content= jsonSlurper.parseText '''     
[{"dates": {
            "2021-02-08": "8",
            "2021-02-09": "8",
            "2021-02-10": "8",
        }}]
'''

arrayList = [];
newArrayList = [];
finalArrayList = []

arrayList = content[0].dates.toString().substring(1,content[0].dates.toString().length() - 1).split(',')


for (i = 0; i < arrayList.size(); i++){
      newArrayList.add(arrayList[i].split('='))
    }

for (i = 0; i < newArrayList.size(); i++){
    finalArrayList.add('{"date": "'+ newArrayList[i][0]+ '", "value": "' + newArrayList[i][1] + '"}')
    }

content[0].dates = finalArrayList

println(content[0].dates)

Upvotes: 0

Related Questions