我使用xml2js节点将json对象转换为xml文件。我想在解析我的json时设置数组项的元素名称
{
"myValue": "1",
"myItems": [
"13",
"14",
"15",
"16"
]
}我希望它看起来像(并将"element“标签设置为"myItem")
<root>
<myItems>
<element>13</element>
<element>14</element>
<element>15</element>
<element>16</element>
</myItems>
<myValue>1</myValue>
</root>但是xml2js只要给我
<root>
<myItems>13</myItems>
<myItems>14</myItems>
<myItems>15</myItems>
<myItems>16</myItems>
<myValue>1</myValue>
</root>有没有需要设置的选项,或者我需要以某种方式格式化我的json?能够设置"element“标签名称吗?今天我有最新的xml2js更新。
发布于 2017-07-25 06:27:27
尝试将您的JSON重新格式化为如下所示。
{
"myValue": "1",
"myItems": {
"myItem": [
"13",
"14",
"15",
"16"
]
}
}发布于 2018-06-16 03:01:05
这个问题正在GitHug上讨论:https://github.com/Leonidas-from-XIV/node-xml2js/issues/428
基于@Stucco的回答,我创建了一个简单的函数,将数组嵌套在所需的名称下:
var item = {
word: 'Bianca',
vowels: [ 'i' ],
bannedVowels: [ 'a' ],
syllabs: [ 'Bian', 'ca' ],
sounds: [ 'an' ]
};
var output = {};
_.each(item, function(value, key) {
// this is where the magic happens
if(value instanceof Array)
output[key] = {"item": value};
else
output[key] = value;
})
var builder = new xml2js.Builder({rootName: "item"});
var xml = builder.buildObject(output);上面的例子给出了这个XML:
<item>
<word>Bianca</word>
<vowels>
<item>i</item>
</vowels>
<bannedVowels>
<item>a</item>
</bannedVowels>
<syllabs>
<item>Bian</item>
<item>ca</item>
</syllabs>
<sounds>
<item>an</item>
</sounds>
</item>但是,如果数组嵌套得更深,我的简单函数将需要调整。
https://stackoverflow.com/questions/43673396
复制相似问题