Subburaj
Subburaj

Reputation: 5192

Append json into a json in groovy

I am newbie to groovy. My requirement is i have to append a json into a json.My code as follows:

JSON constructed by me:

def builder = new groovy.json.JsonBuilder()
   def root=builder.event{                
            type  "model_output_load_init"
            time new Timestamp(date.getTime())
            status "success"                        
        }

JSON from DB:

def json = rs.getString("status");

Now i have to append constructed into the JSON From DB. PLease help me to solve this.Thanks in advance.

EDIT:

My Constructed JSON:

{
    "event": {
        "type": "model_output_load_init",
        "time": "2015-10-01T14:08:17+0000",
        "status": "success"
    }
}

JSON FROM DB:

{
    "model_build": {
        "Initialized": {
            "Timestamp": ""
        }
    },
    "modelExec": {
        "Initialized": {
            "Timestamp": ""
        }
    }
}

OUTPUT NEEDED:

{
    "model_build": {
        "Initialized": {
            "Timestamp": ""
        }
    },
    "modelExec": {
        "Initialized": {
            "Timestamp": ""
        }
    },
    "event": {
        "type": "model_output_load_init",
        "time": "2015-10-01T14:08:17+0000",
        "status": "success"
    }

}

Upvotes: 2

Views: 16851

Answers (1)

Emmanuel Rosa
Emmanuel Rosa

Reputation: 9885

You can append to the Map generated by JsonSlurper.

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def builder = new JsonBuilder()
def root = builder.event{                
    type  "model_output_load_init"
    time new Timestamp(date.getTime())
    status "success"                        
}

// Simulates the JSON from DB
def json = new JsonSlurper().parseText('''
{
    "model_build": {
        "Initialized": {
            "Timestamp": ""
        }
    },
    "modelExec": {
        "Initialized": {
            "Timestamp": ""
        }
    }
}''')

// Append the built JSON to the "slurped" JSON
json.event = root.event

// Re-build the JSON so it can saved as a String
new JsonBuilder(json).toPrettyString()

The output looks like this:

{
    "event": {
        "type": "model_output_load_init",
        "time": "2015-10-01T14:39:11+0000",
        "status": "success"
    },
    "modelExec": {
        "Initialized": {
            "Timestamp": ""
        }
    },
    "model_build": {
        "Initialized": {
            "Timestamp": ""
        }
    }
}

Upvotes: 6

Related Questions