Marvin Budd
Marvin Budd

Reputation: 491

Convert entities when parsing XML to JSON using xml2js?

I'm using a class to convert xml to json for my project like so:

export class AccessionClass {
  constructor(accessionFilename) {
    this.accessionFilename = accessionFilename
    this.accessionXML = fs.readFileSync(this.accessionFilename).toString()
    const parser = new xml2js.Parser({ explicitArray: false })
    parser.parseString(this.accessionXML, (err, results) => {
      this.accessionJSON = results.accessions
    })...
  getJSONItem(itemNumber, callback) {
    let oneItem
    let items = this.accessionJSON.item.filter(item => {
      return item.accession === itemNumber
    })
    if (items.length > 1) {
      console.log('getJSONItem: ' + items.length + ' items for accession: ' + itemNumber)
    }
    callback(items[0])
  }

After calling getJSONItem the JSON string values have unconverted entities

(' & ...)

Am I missing an obvious option to do this? What is the best way to get these converted?

Upvotes: 0

Views: 204

Answers (2)

etcUniversal
etcUniversal

Reputation: 1

I know there's no other way you're going to do this with your hand to organize it.

Upvotes: -1

Marvin Budd
Marvin Budd

Reputation: 491

On closer inspection of the above you may observe that the entities were munged by something in my xml. Fixing that solved my problem! I'll just have to hand edit them to fix them. Sorry for the false alarm.

Upvotes: 0

Related Questions