Search code examples
jsongroovymergejenkins-pipelinejenkins-groovy

Create json object and append json into existing json file using Groovy


I'm pretty new to Groovy (and json) and plauing arround to get the expected solution. But couldn't be able to achive it. What I'm trying to do is parse an existing json file and then add/append additional entries as in below example:

Original Json File:

{
    "stack-1": {
        "name": "demo",
        "createdAt": "11:00 PM",
        "owner": "sarva",
        "dbName": "DB"
    }
}

New Json Content from Json Builder:

{
    "stack-2": {
        "name": "demo-2",
        "createdAt": "15:00 PM",
        "owner": "bhowma",
        "dbName": "DB2"
    }
}

Intended Json output after merge:

{
    "stack-1": {
        "name": "demo",
        "createdAt": "11:00 PM",
        "owner": "sarva",
        "dbName": "DB"
    },
    "stack-2": {
        "name": "demo-2",
        "createdAt": "15:00 PM",
        "owner": "Bhowma",
        "dbName": "DB2"
    }
}

I've tried many variations on the following code snippet but still not quite getting the right format for my intended output.

import groovy.json.*
def number = 2
def name = "demo-2"
def createdAt = "15:00 PM"
def owner = "bhowma"
def db_name = "DB2"

// here I am loading an old json file
def jsonSlurper = new JsonSlurper()
def json = jsonSlurper.parse(new File('/tmp/sarva.json'))

// Here I am building a new JSON with the above parameters.
def builder = new JsonBuilder()
def root = builder "stack-$number": [name: name, createdAt: createdAt, owner: owner, dbName: db_name]
def newJson = jsonSlurper.parseText(builder.toPrettyString())
println(json.getClass())
println(newJson.getClass())
print json
print builder

Currently, I am able to see below the o/p from both json & builder.toPrettyString() and their classes. but I am not able to merge them as intended. and I want this merge to work for as many json objects as I pass.

Current output looks like below

class groovy.json.internal.LazyMap
class groovy.json.internal.LazyMap
[stack-1:[createdAt:11:00 PM, dbName:DB, name:demo, owner:sarva]]
{"stack-2":{"name":"demo-2","createdAt":"15:00 PM","owner":"Bhowma","dbName":"DB-2"}}

Any help sorting this would be much appreciated.


Solution

  • Ignoring your example being incomplete, you've parsed the original JSON into a Map, so just add the new element to the map

    // Here I am building a new Map with the above parameters.
    json += ["stack-$number": [name: name, createdAt: createdAt, owner: owner, dbName: db_name]]
    

    And then print out the new json from this map

    println new JsonBuilder(json).toPrettyString()