0

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?

2 Answers 2

2

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

Comments

0

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)

1 Comment

This might work here but will explode with different data, as "toString" is not a suitable serialization format.

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.