gpt4 book ai didi

json - 以 Grails 格式呈现 Json

转载 作者:行者123 更新时间:2023-12-02 13:57:59 25 4
gpt4 key购买 nike

我正在做这样的事情:

def prods = Product.executeQuery("select category.id,category.name, avg(competition1Price), avg(competition2Price), avg(onlineCompetitionPrice) from Product group by category.id")
def output = [[:]]
prods.each { result ->
def prod = ['category_id':result[0],'category_name':result[1],'Competition1Price':result[2],'competition2Price':result[3],'onlineCompetitionPrice':result[4]]
output << prod
}
render output as JSON

我得到的输出是这样的:
 [{},{"category_id":1,"category_name":"Colchones y","Competition1Price":1657.4784,"competition2Price":2071.5,"onlineCompetitionPrice":1242.5}]

我想要的是:
像这样的东西..
   {collection:[{"category_id":"1","category_name":"Colchones y",so on...]}

有人可以帮忙吗..
如何操作json数据的格式..

最佳答案

如果这是您想要的格式,则需要执行以下操作:

def prods = Product.executeQuery("select category.id,category.name, avg(competition1Price), avg(competition2Price), avg(onlineCompetitionPrice) from Product group by category.id")
def output = [collection:[]]
prods.each { result ->
def prod = ['category_id':result[0],'category_name':result[1],'Competition1Price':result[2],'competition2Price':result[3],'onlineCompetitionPrice':result[4]]
output.collection << prod
}
render output as JSON

或者(可以说更整洁):
def prods = Product.executeQuery("select category.id,category.name, avg(competition1Price), avg(competition2Price), avg(onlineCompetitionPrice) from Product group by category.id")
def prodlist = prods.collect { result ->
[ 'category_id': result[0],
'category_name': result[1],
'Competition1Price':result[2],
'competition2Price':result[3],
'onlineCompetitionPrice':result[4] ]
}
render [ collection: prodlist ] as JSON

关于json - 以 Grails 格式呈现 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12458087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com