Home > database >  Convert entities when parsing XML to JSON using xml2js?
Convert entities when parsing XML to JSON using xml2js?

Time:03-19

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related