1

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:

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?

DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127

1 Answers1

0

You are trying to require() an XML file, which executes the XML as if it was JSON/JavaScript.

You need to pass the path ./file.xml as a String, but running require('./file.xml') reads it and treats it as code.

Replace the require('./file.xml') with './file.xml'.

0xLogN
  • 3,289
  • 1
  • 14
  • 35