英文:
Generate JSON based on map keys names
问题
我是新手学习Groovy,有一个任务。我有一个看起来像这样的Map:
[sessionCampaignName:renins_KASKO_May23, sessionMedium:Yandex_banners, sessionSource:Media]
或者
[sessionCampaignName:olv_May23, sessionTerm:greatjob]
如何基于地图键名构建一个JSON,再加上一个名为date
的额外JSON属性(例如,让我们以第一个例子为例):
[
{
"name": "date"
},
{
"name": "sessionCampaignName"
},
{
"name": "sessionMedium"
},
{
"name": "sessionSource"
}
]
尝试过以下方法:
List dimensionsList = convertedMap.collect { dimensionName, dimensionValue ->
[
[
name: 'date'
],
[
name: dimensionName
]
]
}
String jsonDimensions = JsonOutput.toJson(dimensionsList)
但没有达到我预期的效果。有什么建议吗?
英文:
I'm new to Groovy and I've a task. I have a Map looks like:
[sessionCampaignName:renins_KASKO_May23, sessionMedium:Yandex_banners, sessionSource:Media]
or
[sessionCampaignName:olv_May23, sessionTerm:greatjob]
How can i build a JSON based on map keys names + additional json property called date
like (for example lets take 1st case):
[
{
"name": "date"
},
{
"name": "sessionCampaignName"
},
{
"name": "sessionMedium"
},
{
"name": "sessionSource"
}
]
Tried with:
List dimensionsList = convertedMap.collect {dimensionName, dimensionValue ->
[
[
name: 'date'
],
[
name: dimensionName
]
]
}
String jsonDimensions = JsonOutput.toJson(dimensionsList)
But didn't reach what I expected to reach. Any tips?
答案1
得分: 2
尝试如下-
def map = [sessionCampaignName: 'renins_KASKO_May23', sessionMedium: 'Yandex_banners', sessionSource: 'Media']
List dimensionsList = [['name': 'date']] + map.keySet().collect { key ->
['name': key]
}
/*
List dimensionsList = map.keySet().collect([name: 'date']) { key ->
[name: key]
}
*/
String jsonDimensions = new groovy.json.JsonBuilder(dimensionsList).toPrettyString()
println jsonDimensions
输出:
[
{
"name": "date"
},
{
"name": "sessionCampaignName"
},
{
"name": "sessionMedium"
},
{
"name": "sessionSource"
}
]
英文:
Try as below-
def map = [sessionCampaignName: 'renins_KASKO_May23', sessionMedium: 'Yandex_banners', sessionSource: 'Media']
List dimensionsList = [['name': 'date']] + map.keySet().collect { key ->
['name': key]
}
/*
List dimensionsList = map.keySet().collect([[name: 'date']]) { key ->
[name: key]
}
*/
String jsonDimensions = new groovy.json.JsonBuilder(dimensionsList).toPrettyString()
println jsonDimensions
Output:
[
{
"name": "date"
},
{
"name": "sessionCampaignName"
},
{
"name": "sessionMedium"
},
{
"name": "sessionSource"
}
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论