I am trying to convert an XML file into JSON using xml2js on Node.JS.
When I hit an attribute, it will give a '_' and '$' characters as replacement.
I am fully aware that JSON does not have the concept of attributes that XML does.
How do I convert the following XML document:
<id>
<name language="en">Bob</name>
<name>Alice</name>
</id>
Into a JSON format something like:
{
"id": {
"name": [{
"language": "en",
"text": "bob"
}, "alice"]
}
}
My code in Node.JS is:
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 }));
});
The current output is:
{ id: { name: [ { _: 'Bob', '$': { language: 'en' } }, 'Alice' ] } }
will output
{
id: { name: [ { language: 'en', text: 'Bob' }, { text: 'Alice' } ] }
}
the code:
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 }));
});
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加