2 回答
TA贡献1842条经验 获得超21个赞
为此,您可以使用camaro。camaro 允许您编写一个基于 xpath 的模板来指定您想要的输出方式。在这种情况下,你指定你想要一个数组
const { transform } = require('camaro')
const xml = `<Shift>
<Transaction>
<Currency>GBP</Currency>
<Amount>24.50</Amount>
</Transaction>
<Transaction>
<Currency>GBP</Currency>
<Amount>25.50</Amount>
</Transaction>
<Transaction>
<Currency>GBP</Currency>
<Amount>26.50</Amount>
</Transaction>
<Transaction>
<Currency>GBP</Currency>
<Amount>27.50</Amount>
</Transaction>
</Shift>`
;(async function () {
const template = {
transactions: ['/Shift/Transaction', {
Currency: 'Currency',
Amount: 'Amount'
}]
}
console.log(await transform(xml, template));
})()
输出
{ transactions:
[ { Currency: 'GBP', Amount: '24.50' },
{ Currency: 'GBP', Amount: '25.50' },
{ Currency: 'GBP', Amount: '26.50' },
{ Currency: 'GBP', Amount: '27.50' } ] }
即使只有 1 个元素
const { transform } = require('../')
const xml = `<Shift>
<Transaction>
<Currency>GBP</Currency>
<Amount>24.50</Amount>
</Transaction>
</Shift>`
;(async function () {
const template = {
transactions: ['/Shift/Transaction', {
Currency: 'Currency',
Amount: 'Amount'
}]
}
console.log(await transform(xml, template));
})()
输出
{ transactions: [ { Currency: 'GBP', Amount: '24.50' } ] }
TA贡献1858条经验 获得超8个赞
有很多 XML 到 JSON 转换器,它们都有这种问题。它们在某些情况下会做您想做的事,而在其他情况下则不会,而且它们都没有提供太多控制权。如果您想控制生成的 JSON,我建议使用 XSLT 3.0:这允许您在调用xml-to-json()
进行转换之前将 XML 转换为与您想要生成的 JSON 的结构相对应。
添加回答
举报