user4433161
user4433161

Reputation:

Groovy to create JSON

Here's an SQL query I had to execute in Groovy:

def resultset_bio = sql.rows("SELECT author, isbn FROM Book WHERE genre = 'biography'")

I'm trying to convert this data into JSON. For that, I am using this code:

def json = new groovy.json.JsonBuilder()
            json {
                Biographies(resultset_bio.collect{[id: it]})
            }
            println json.toPrettyString()
        }

The JSON output I expect should be like this:

    {
    "Biographies":
        {
            "SSS": ["XXX",456988]
        }
}

But instead, I'm getting this:

{
    "Biographies": [
        {
            "id": {
                "author": "XXX",
                "isbn": 456988,
            }
        }
    ]
}

How should I change my code? Please help.

Upvotes: 1

Views: 813

Answers (2)

Dylan Bijnagte
Dylan Bijnagte

Reputation: 1356

You do not have the book title in your select so you can't make a mapping of title to book info.

In order to get the list layout of each row (which is a map) grouped by author:

def authorBios = resultset_bio.groupBy { it.author }

def biographies = authorBios.collectEntries { author, row ->
     [author, row*.values()] 
}
json {
    Biographies(biographies)
}

Upvotes: 0

Opal
Opal

Reputation: 84786

Now id is passed as a static key. Try:

json {
   Biographies(resultset_bio.collect{[(it.id): it]})
}

Upvotes: 1

Related Questions