在Groovy中转置JSON



我有一个JSON:

{
"range": "'All traffic",
"majorDimension": "ROWS",
"values": [
[
"Date",
"Sessions",
"Leeds",
"Сontact_query",
"wo_Сontact_query"
],
[
"20200107",
"3461",
"15",
"0",
"15"
],
[
"20200115",
"7824",
"43",
"0",
"43"
]
]
}

包含index[0]values数组中的元素是JSON属性的名称。我想将这些名称与以索引[0+]开头的值进行映射。每个索引的值的数量可以不同。映射应该是动态的,没有硬索引。

我想得到以下JSON:

[
{
"Date": "20200107",
"Sessions": "3461",
"Leeds": "15",
"Contact_query": "0",
"wo_Contact_query": "15"
},
{
"Date": "20200115",
"Sessions": "7824",
"Leeds": "43",
"Contact_query": "0",
"wo_Contact_query": "43"
}
] 

我用有点奇怪的JOLT配置成功地做到了:

[
{
"operation": "shift",
"spec": {
"values": {
"0": null,
"*": {
"*": "[&1].@(2,[0].[&])"
}
}
}
},
{
"operation": "shift",
"spec": {
"0": null,
"*": "[]"
}
}
]

但是我想用Groovy脚本代替它。

我得到了以下解决方案:

def slurped = new JsonSlurper().parseText(text)
def val = slurped.values[0]
def json = slurped.values.collect{
[val, it].transpose().collectEntries() 
}

但它也返回[0] element的值,我应该跳过:

{
"Date":"Date",
"Sessions":"Sessions",
"Leeds":"Leeds",
"Contact_query":"Contact_query",
"wo_Contact_query":"wo_Contact_query"
}

我如何改进解决方案?

您可以使用pop删除集合的第一个值:

def values = new groovy.json.JsonSlurper().parseText(text).values;
def val = values.pop()
def json = values.collect { [val, it].transpose().collectEntries()  }

另一个使用headtail的选项:

def json = new JsonSlurper().parseText(data)
def head = json.values.head() // first element, the "head"
def tail = json.values.tail() // the rest, excluding the head, i.e. "tail"
def result = tail.collect { [head, it].transpose().collectEntries() }

最新更新