Home > front end >  Groovy script: Not able to add object in json
Groovy script: Not able to add object in json

Time:05-20

Not able to append object value. trying to transform json to expected output having all the user infomration.

Groovy Script:

import groovy.json.*;

def data='''{"totalcount":5,"employees":[{"name":"Sam","age":34},{"name":"Richard","age":38},{"name":"Harry","age":36},{"name":"Tom","age":40},{"name":"David","age":84},{"name":"Chris","age":52}],"Salaries":[{"name":"Sam","salary":34000},{"name":"Richard","salary":89889},{"name":"Harry","salary":36898},{"name":"David","salary":489889},{"name":"Chris","salary":84898},{"name":"Toms","salary":5298}]}'''

def test = new JsonSlurper().parseText(data)
def a=[:]
def OU=[:]
def status=[]
a.OUTPUT=OU
OU.STATUS=status
def b = [:]
for(def y=0;y<test.employees.size();y  ) {
for (def j = 0; j < test.Salaries.size(); j  ) {
if (test.employees[y].name ==test.Salaries[j].name ) {
b.name = test.employees[y].name
b.age = test.employees[y].age
b.salary = test.Salaries[j].salary
status<<b
j=test.Salaries.size()
}
}
}
String finalJson = JsonOutput.toJson a;
println JsonOutput.prettyPrint( finalJson)

Expected Result :
{"OUTPUT":{"STATUS":[{"name":"Sam","age":34,"salary":34000},{"name":"Richard","age":38,"salary":89889},{"name":"Harry","age":36,"salary":36898},{"name":"David","age":84,"salary":489889},{"name":"Chris","age":52,"salary":84898}]}}

CodePudding user response:

You can simplify your code to:

import groovy.json.*

def data='{"totalcount":5,"employees":[{"name":"Sam","age":34},{"name":"Richard","age":38},{"name":"Harry","age":36},{"name":"Tom","age":40},{"name":"David","age":84},{"name":"Chris","age":52}],"Salaries":[{"name":"Sam","salary":34000},{"name":"Richard","salary":89889},{"name":"Harry","salary":36898},{"name":"David","salary":489889},{"name":"Chris","salary":84898},{"name":"Toms","salary":5298}]}'

def test = new JsonSlurper().parseText(data)

def joinedByName = (test.employees   test.Salaries).groupBy { it.name }

def result = [
    OUTPUT: [
        STATUS: [
            joinedByName.collect { it.value.inject { a, b -> a   b } }
                        .findAll { it.salary && it.age } // Remove people who don't have both
        ]
    ]
]
String finalJson = JsonOutput.toJson result;
println JsonOutput.prettyPrint(finalJson)
  • Related