Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - Constructing json from String

I'm using Groovy, i've tried to create a simple function which will construct a Json object from a provided Json string, then i'm trying to print this string but unfortunate it's adding Square brackets to the output.

Here's a snippet from my code:

def JsonBuilder ConstructJsonObject (jsonStr) {
    def jsonToReturn = new JsonBuilder();
    def root = jsonToReturn(jsonStr);
    return jsonToReturn;
}

String jsonStr = "{id: '111'}";
println(jsonStr);
def jsonObject = ConstructJsonObject(jsonStr);
println(jsonObject.toPrettyString());

And here's the output:

{id: '111'}

[ "{id: '111'}" ]

It's returning an Array and not a pure Json.

like image 665
Alex Brodov Avatar asked Dec 04 '25 11:12

Alex Brodov


1 Answers

If you change your input to be valid json (with double quotes round the keys and values), you can do:

import groovy.json.*

String jsonStr = '{"id": "111"}'
println new JsonBuilder(new JsonSlurper().parseText(jsonStr)).toPrettyString()

To print

{
    "id": "111"
}
like image 182
tim_yates Avatar answered Dec 07 '25 00:12

tim_yates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!