Groovy脚本:无法在json中添加对象

jc3wubiy  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(202)

无法附加对象值。正在尝试将json转换为包含所有用户信息的预期输出。
Groovy脚本:

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}]}}
mtb9vblg

mtb9vblg1#

您可以将代码简化为:

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)

相关问题