jsongroovyjsonslurperjsonbuilder

Store multiple key:value pairs inside json object


I am very new with groovy scripts. I would like to build a JSON output using responses from an api that I query. Since I want to build the JSON file dynamically over multiple queries, I am using a map.

I want to store multiple key:value pairs in a JSON object.

My code looks like this

def map = [
            'result': []
    ]

    def response = /* doing api reguest */

    map.result << [respose_key1_1: "response_value 1_1"]
    map.result << [response_key1_2: "response_value 1_2"]

    def json = new JsonBuilder()

    json rootKey: map

    println JsonOutput.prettyPrint(json.toString())

returns this

{
    "rootKey": {
        "result": [
            {
                "respose_key1_1": "response_value 1_1"
            },
            {
                "response_key1_2": "response_value 1_2"
            }
        ]
    }
}

What I need

{
    "rootKey": {
        "result": {
            "respose_key1_1": "response_value 1_1",
            "response_key1_2": "response_value 1_2"
        }
    }
}

Solution

  • This is an array:

    def map = [
       result: [] // this is an array literal
    ]
    

    This is a map:

    def map = [
      result: [:]  // this is a map literal
    ]
    

    While technically this will work:

       map.result << [respose_key1_1: "response_value 1_1"]
       map.result << [response_key1_2: "response_value 1_2"]
    

    It could be simplified to this:

    map.result.response_key1_1 = "response_value 1_1"
    map.result.response_key1_2 = "response_value 1_2"
    

    The above eliminates extraneous map construction.