3

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.

Alex Brodov
  • 3,365
  • 18
  • 43
  • 66
  • Have you tried the JsonSlurper? If you want to parse JSON from a string: http://www.groovy-lang.org/json.html – rhinds Oct 20 '15 at 16:07

1 Answers1

8

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"
}
tim_yates
  • 167,322
  • 27
  • 342
  • 338