我试图使用Jolt库将一个json转换为另一个json,但没有得到想要的输出。
以下是我的输入文件。
{ "maxResults": 150, "总数": 89, "问题": [ { "key": "1", "fields": { "fixVersions": [ { "self": "FIX1-01", "id": "11"}, { "self": "FIX1-02", "id": "12"} } ] } }, { "key": "2", "字段": { "fixVersions": [ { "self": "FIX2-01", "id": "21" } ] }。 }, { "key": "3", "字段": { "fixVersions": [] } } ] }
And this is the spec file I am using for transformation.
<pre>
[
{
"operation": "shift",
"spec": {
"issues": {
"*": {
"key": "[&1].id",
"fields": {
"fixVersions": {
"*": {
"self": "[&1].fixVersion.name"
}
}
}
}
}
}
}
]
而我得到的是这样的输出
[ { "id" : "1", "fixVersion" : { "name" : [ "FIX1-01", "FIX2-01" ] }。 }, { "fixVersion" : { "name" : "FIX1-02" }, "id" : "2" }, { "id" : "3" }。]
这是不对的,它所做的是获取每个问题的第一个自字段值并将其作为一个数组填充到输出的第一个fixVersions中,然后获取第二个自字段值并将其填充到第二个fixVersions中。它所做的是获取每个问题的第一个自字段值,并将其作为一个数组填充到输出的第一个fixVersions中,然后获取第二个自字段值,并将其填充到第二个fixVersions中。我想做的是保持输入中的结构,只是改变自字段的名称,像这样。
[ { "id" : "1", "fixVersion" : [ { "name" : "FIX1-01" }, { "name" : "FIX1-02" } ] }, { "fixVersion" : [ { "name" : "FIX2-01" } ], "id" : "2" }, { "id" : "3" }。]
我做错了什么?
看看这个规范是否是你正在寻找的。
[
{
"operation": "shift",
"spec": {
"issues": {
"*": {
"key": "[&1].id",
"fields": {
"fixVersions": {
"*": {
"self": "[&4].fixVersion[&1].name"
}
}
}
}
}
}
}
]
根据你的输入进行输出,结果是:
[ {
"id" : "1",
"fixVersion" : [ {
"name" : "FIX1-01"
}, {
"name" : "FIX1-02"
} ]
}, {
"id" : "2",
"fixVersion" : [ {
"name" : "FIX2-01"
} ]
}, {
"id" : "3"
} ]
请注意在你使用的索引上的变化,以重建fixVersion(需要考虑到who issues索引)列表,你缺少了这个。
[&4].fixVersion[&1].name
由于你已经使用了XSLT标签和Java标签,你可以使用XSLT或XQuery 3与Saxon 9一起使用,例如
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare option output:method 'text';
declare variable $json as xs:string external := '{
"maxResults": 150,
"total": 89,
"issues": [
{
"key": "1",
"fields": {
"fixVersions": [
{
"self": "FIX1-01",
"id": "11"
},
{
"self": "FIX1-02",
"id": "12"
}
]
}
},
{
"key": "2",
"fields": {
"fixVersions": [
{
"self": "FIX2-01",
"id": "21"
}
]
}
},
{
"key": "3",
"fields": {
"fixVersions": []
}
}
]
}';
transform(map {
'source-node' : json-to-xml($json),
'stylesheet-node' : <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="*:string[@key = 'self']">
<xsl:copy>
<xsl:attribute name="key">name</xsl:attribute>
<xsl:value-of select="."/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
})?output => xml-to-json(map { 'indent' : true() })