In Node.js, fast-xml-parse is only returning a single object instead of an array

Currently, I am working on implementing tracking functionality using a specific service that provides responses in XML format. For parsing the XML response, I have opted to utilize the fast-xml-parser package. However, I have encountered an issue:

Everything works smoothly when there is only one item in the response. But when multiple items are present, like in the following example:

<xsd:events xmlns:xsd="http://somelink/xsd">
        <event id=“1234”>
          <packetCode>ABC123</packetCode>
          <eventCode>EVENT_CODE</eventCode>
          <eventDate>2020-12-03T14:34:09.000+02:00</eventDate>
          <stateCode>STATUS_CODE</stateCode>
          <eventSource zip=“123">Some place</eventSource>
        </event>
        <event id=“456”>
          <packetCode>DEF456</packetCode>
          <eventCode>EVENT_CODE</eventCode>
          <eventDate>2020-12-03T14:40:44.000+02:00</eventDate>
          <stateCode>STATUS_CODE</stateCode>
          <eventSource zip=“123">Some place</eventSource>
        </event>
      </xsd:events>

After executing the code:

const xmlParser = require('fast-xml-parser');
xmlParser.parse(exampleXml);

I noticed that the resulting object only contains the data of the last element:

{
    'xsd:events': {
      event: {
        packetCode: 'DEF456',
        eventCode: 'EVENT_CODE',
        eventDate: '2020-12-03T14:40:44.000+02:00',
        stateCode: 'STATUS_CODE',
        eventSource: 'Some place',
      }
    }
  }

instead of having an array with both events as expected. Ideally, the output should resemble:

{
    'xsd:events': [{/* event data */}, {{/* event data */}]
  }

I am seeking assistance and advice on what might be going wrong, whether certain options are required or if something else needs to be adjusted. Your help and guidance would be greatly appreciated.

Answer №1

The issue arises from the presence of curly quotes instead of regular quotes ".

This problem often occurs when content is copied and pasted from Word or MS Office, as these programs sometimes automatically convert standard quotes into “smart quotes”, which are directional and curly in shape. These smart quotes are different from regular quotes and can cause parsing errors because they consist of multiple bytes. If not properly encoded, they may be misinterpreted as separate characters.

To resolve this issue, make sure to use standard quotes in XML:

<xsd:events xmlns:xsd="http://somelink/xsd">
    <event id="1234">
      <packetCode>ABC123</packetCode>
      <eventCode>EVENT_CODE</eventCode>
      <eventDate>2020-12-03T14:34:09.000+02:00</eventDate>
      <stateCode>STATUS_CODE</stateCode>
      <eventSource zip="123">Some place</eventSource>
    </event>
    <event id="456">
      <packetCode>DEF456</packetCode>
      <eventCode>EVENT_CODE</eventCode>
      <eventDate>2020-12-03T14:40:44.000+02:00</eventDate>
      <stateCode>STATUS_CODE</stateCode>
      <eventSource zip="123">Some place</eventSource>
    </event>
  </xsd:events>

By adopting regular quotes, the XML will correctly produce the desired JSON output with an array of two event objects:

{
    "xsd:events": {
        "event": [
            {
                "packetCode": "ABC123",
                "eventCode": "EVENT_CODE",
                "eventDate": "2020-12-03T14:34:09.000+02:00",
                "stateCode": "STATUS_CODE",
                "eventSource": "Some place"
            },
            {
                "packetCode": "DEF456",
                "eventCode": "EVENT_CODE",
                "eventDate": "2020-12-03T14:40:44.000+02:00",
                "stateCode": "STATUS_CODE",
                "eventSource": "Some place"
            }
        ]
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing an element from the parent/master array after splicing the copied array

My array setup includes a master array called the parent array. When the page loads, a PHP array encoded in JSON with information about every user on the site is assigned to a JavaScript variable - var all_users = <?php echo $users;?>;. Upon logging ...

Contrasting Template Helper and Template Variable in Meteor.js

What sets apart the use of a Template Helper from a Template Variable (if that's not the right term)? How do you determine when to utilize each one? In the following example, both Template.apple.price function and the quantity function in Template.ap ...

Encountering an issue with React where the useContext hook is returning undefined instead of

I am facing an issue where I am attempting to access state and setState from the Store file, but it returns as undefined. Can someone help me understand what is causing this problem and how I can resolve it? import React, {createContext, useState} from &ap ...

Having difficulty with pagination within a callback function

I have been attempting to paginate in a call to a callback function, but I am encountering an error on the second call. Here is what my function does: let content = '' let size = 100 let from = 1 function result(size, from, callback) { ap ...

What is the most effective way to alphabetically organize a Javascript array?

Is there a more professional way to sort people alphabetically by last name in an array? Here is the array I'm working with: const people = [ 'Bernhard, Sandra', 'Bethea, Erin', 'Becker, Carl', 'Bentsen, Lloyd' ...

Encountering difficulties with image processing on a web page

Recently, I've been experimenting with uploading an image and converting it to a grayscale version on my webpage. Oddly enough, the javascript code works perfectly when tested locally but fails to generate the grayscale image once integrated onto the ...

The promise of a MongoDB connection with Node.js returns as 'awaiting fulfillment'

Greetings to all! A few weeks ago, I embarked on the journey of learning javascript, node.js and mongo. As a beginner, I have an interesting task at hand today. My goal is to add a simple document to the mongoDB and perform a conditional check. So here&apo ...

Issues with z-index in a multi-column menu using React-Router are causing unexpected behavior

I am currently working on a multi-tier, multi-column menu created using the https://github.com/kontentino/react-multilevel-dropdown library. However, I am facing an issue where the submenu items are appearing under the main items despite several attempts t ...

Guide to utilizing Terser in conjunction with webpack

I am currently using Webpack 6.10.2 in combination with Vue 3.9.3. I encountered an issue with Uglify.js when running npm run build due to its inability to handle ES6 code. To work around this problem, I followed the recommendation of removing Uglify fro ...

The jqGrid displaying data with datatype set to "jsonstring" is only showing the first page

When my JqGrid receives data from the server in JSON format, I use the following parameters: _self.GridParams = { rows: 7, page: 1, sidx: '', sord: '' } Once the data is retrieved, it is stored in the variable 'data': Objec ...

I am currently working on obtaining images that are saved by their URL within a PHP file. These images are located within a directory named "images."

My code is incomplete and not functioning as expected. $.get("museums.php",function(data,status){ var response=''; //console.log(data); var json = $.parseJSON(data); museums = json.museums; for(let m in museums) { $("#na ...

Transfer shader program with buffers from shadertoy to three.js

Currently, I am delving into the world of webgl and shaders to enhance my understanding and skills. My objective is to create animations for website backgrounds. I have successfully imported basic examples from shadertoy into three.js and have been experim ...

Converting constants into JavaScript code

I've been diving into typescript recently and came across a simple code snippet that defines a constant variable and logs it to the console. const versionNuber : number = 1.3; console.log(versionNuber); Upon running the tsc command on the file, I no ...

Using React router to handle multiple hierarchical parameters

Having a documentation component in my app, I want the URLs to appear as follows: url: myapp.com/docs url: myapp.com/docs/document-1 url: myapp.com/docs/category-1/document-2 url; myapp.com/docs/category-1/category-2/document-2 The challenge lies in set ...

Changing the content of the initial post in a loop on WordPress

<?php $freeadvice=new WP_Query('category_name=freeadvice&showposts=10'); while($freeadvice->have_posts() ): $freeadvice->the_post(); ?> <li class="event"> <input type="radio" name="tl-group" /> ...

Having trouble with JSFIDDLE not functioning properly on my website

I'm having an issue with implementing a JSFIDDLE on my web form. The fiddle itself is working perfectly fine, but for some reason, I can't get it to work on my page. Can someone please help me figure out what mistake I might be making? Here is th ...

The Vue component seems to be missing the definition of $v for Vuelidate

I've been struggling to resolve this issue. The error message I am encountering pertains to a Vue component that is utilizing the Vuelidate library for form validation. Do you have any insights on what might be causing this error? Uncaught TypeError: ...

Delete the generated thumbnails from the input JavaScript file

One issue I'm facing is that I have written JavaScript code to generate a thumbnail when a user uploads an image. Now, I would like to implement a feature that allows the user to click on an "X" button to delete the uploaded image. This is the existi ...

Retrieving the user's Windows username with JavaScript

Is it possible to retrieve the Windows user name solely in Internet Explorer using the code below? function GetUserName() { var wshell = new ActiveXObject("WScript.Shell"); alert(wshell.ExpandEnvironmentStrings("%USERNAME%")); } What methods ...

Switch out text and calculate the frequency of letters in a given string

I have a string that looks like this: "061801850010300-09/A/B". My goal is to replace all "/" with "-" and also change "A" to "1" and "B" to "2". My objective is to assign each letter in the alphabet a numerical value - for example, A as 1, B as 2, C as 3 ...