我正在尝试使用Node.JS上的xml2js将XML文件转换为JSON。
当我点击一个属性时,它将提供一个'_'和'$'字符作为替换。
我完全意识到JSON不具有XML所具有的属性的概念。
如何转换以下XML文档:
<id>
<name language="en">Bob</name>
<name>Alice</name>
</id>
转换为JSON格式,例如:
{
"id": {
"name": [{
"language": "en",
"text": "bob"
}, "alice"]
}
}
我在Node.JS中的代码是:
const fs = require('fs');
const util = require('util');
const json = require('json');
const xml2js = require('xml2js');
const xml = fs.readFileSync('./test.xml', 'utf-8', (err, data) => {
if (err) throw err;
});
const jsonStr = xml2js.parseString(xml, function (err, result) {
if (err) throw err;
console.log(util.inspect(JSON.parse(JSON.stringify(result)), { depth: null }));
});
当前输出为:
{ id: { name: [ { _: 'Bob', '$': { language: 'en' } }, 'Alice' ] } }
答案 0 :(得分:1)
将输出
{
id: { name: [ { language: 'en', text: 'Bob' }, { text: 'Alice' } ] }
}
代码:
const fs = require('fs');
const util = require('util');
const json = require('json');
const xml2js = require('xml2js');
const xml = fs.readFileSync('./test.xml', 'utf-8', (err, data) => {
if (err) throw err;
});
const jsonStr = xml2js.parseString(xml, function (err, result) {
const nameArray = result.id.name;
const newNameArray = nameArray.map(nameValue => {
let text = '';
let attributes = {};
if (typeof nameValue === 'string') {
text = nameValue
} else if (typeof nameValue === 'object') {
text = nameValue['_']
attributes = nameValue['$']
}
return {
...attributes,
text
}
})
const newResult = {
id: {
name: newNameArray
}
}
if (err) throw err;
console.log(util.inspect(JSON.parse(JSON.stringify(newResult)), { depth: null }));
});
答案 1 :(得分:1)
像这样
const xml = `
<id>
<name language="en">Bob</name>
<name>Alice</name>
</id>`
const { transform } = require('camaro')
const template = {
id: {
name: ['id/name', {
lang: '@language',
text: '.'
}]
}
}
;(async function () {
console.log(JSON.stringify(await transform(xml, template), null, 4))
})()
输出
{
"id": {
"name": [
{
"lang": "en",
"text": "Bob"
},
{
"lang": "",
"text": "Alice"
}
]
}
}