Trying to learn to convert XML to JSON so I can convert some old cURL commands to a script I've been reading a few Q&As and wrote the following module:
fs = require('fs')
const xmlFle = require('./file.xml')
const parser = require('xml2json')
module.exports = fs.readFile(xmlFle, 'utf-8', (err, data) => {
if (err) return `err: ${err}`
try {
const json = parser.toJson(data)
console.log('to json ->', json)
} catch (e) {
return `Convert fail: ${e}`
}
})
but for some reason I'm thrown:
/path/to/file/file.xml:1
<Foo>
^
SyntaxError: Unexpected token '<'
reading through a few Q&As I thought my issue was due to setting fs
from Unexpected token < when parsing XML in NodeJS but that didn't prevent the error.
other referenced:
- Unexpected token < reading xml file
- “[SyntaxError: Unexpected token <]” when I try to add documents to my Solr index with my Node/Express app
- Javascript unexpected token '<' when loading XML from model
file.xml:
<Foo>
<Mon>
<Auth>326478326472347823</Auth>
<Signal>foo</Signal>
</Mon>
<Feed>
<Tag>biochemistry</Tag>
</Feed>
</Foo>
I'm not having an issue with the actual conversion:
const parser = require('xml2json')
const xml = `<Foo>
<Mon>
<Auth>326478326472347823</Auth>
<Signal>foo</Signal>
</Mon>
<Feed>
<Tag>biochemistry</Tag>
</Feed>
</Foo>`
console.log('JSON output', parser.toJson(xml))
results:
JSON output {"Foo":{"Mon":{"Auth":"326478326472347823","Signal":"foo"},"Feed":{"Tag":"biochemistry"}}}
Why am I getting an error when trying to read the XML file?