Having trouble receiving the desired JSON format with xml2js, is there a way to resolve this issue?

After attempting to convert an XML file obtained from an external server into JSON using xml2json, it appears that the conversion is not producing a valid JSON output. It seems like there may be an issue with missing quotes for the keys. Are there adjustments that need to be made?

This is the current code:

app.get('/api/convertabstract/:id', async (req, res, next) => {
  var data = '';
  var finaldata = '';

  function translateData(){
    return new Promise(resolve => {

      https.get('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=' + '11748933,11700088' +'&retmode=xml', function(res) {
        if (res.statusCode >= 200 && res.statusCode < 400)  {
          res.on('data', function(data_) { data += data_.toString(); });
          res.on('end', function() {
            parser.parseString(data, function(err, result) {
              finaldata = util.inspect(result, false, null, true);
            }), resolve('done');
          });
        }
      })
    });
  }

  async function callTranslator() {
    const result = await translateData();
    console.log(finaldata.PubmedArticleSet);
    res.send('this is the data:' + finaldata)
  }
  
  callTranslator();

});

JSON output:

{ PubmedArticleSet: {
PubmedArticle: [
{
MedlineCitation: [
{
[32m'$'[39m: { Status: [32m'MEDLINE'[39m, Owner: [32m'NLM'[39m },
PMID: [ { _: [32m'11748933'[39m, [32m'$'[39m: { Version: [32m'1'[39m } } ],
DateCompleted: [ { Year: [ [32m'2002'[39m ], Month: [ [32m'03'[39m ], Day: [ [32m'04'[39m ] } ],
DateRevised: [ { Year: [ [32m'2006'[39m ], Month: [ [32m'11'[39m ], Day: [ [32m'15'[39m ] } ],
Article: [
{
[32m'$'[39m: { PubModel: [32m'Print'[39m },
Journal: [
{
ISSN: [ { _: [32m'0011-2240'[39m, [32m'$'[39m: { IssnType: [32m'Print'[39m } } ],
JournalIssue: [....etc....

Answer №1

It appears that xml2js and xml2json are two distinct libraries with no connection to each other. It seems like you referenced both in your question - which one are you actually utilizing? Xml2js is not designed to produce JSON, rather it generates JavaScript.

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

Deploying NodeJS applications using PM2, with support for both clustered and single instances

Consider the following scenario: The server has a scoped pm2 instance running in the /project directory A new version of the app is pushed to master branch The continuous integration (CI) system builds the new version How can I instruct CI to deploy the ...

Static file delivery issue: Express unable to serve static files

Here is a glimpse at my project setup: -backend -server.js -www -index.html -app.css -bundle.js I'm facing an issue with Express not serving static files for URLs that contain 2 or more slashes like this localhost:3000/product/1 However, it w ...

Struggling to update state data with response data in React, despite the response not being empty

I'm currently working on my first React API application and I am facing an issue where the state data appears to be empty even after assigning res.data, which is not empty. Additionally, I am struggling with rendering all of this content inside a div. ...

Converting ExpressJS Function for Multipart Uploading to AWS Lambda

Looking for advice on converting this Express.js function to AWS Lambda for Node.js 18. const upload = multer() // Write received chunk to S3 bucket app.post('/upload', upload.single("file"), (req, res) => { const { index, fileNam ...

Issue: ENOENT - The specified file or directory, './views/s.ejs', does not exist in Node.js Express

Encountering an error when attempting to render a file from the 'views' directory in the 'routes'. The specific error message is as follows: Error: Valid Login { [Error: ENOENT: no such file or directory, open './views/s ...

Request body is null if accept-encoding is set to 'gzip, deflate'

I'm struggling to capture data from a webhook sent by a third-party source. Despite verifying that the content-length is greater than 0, inspecting req.body only returns {}. The webhook is directed towards the route '/v2/wtevr/report/wtevr'. ...

Is there a way for me to determine if an open port is TCP or HTTP?

Currently, I am using a Windows server (Windows 7), and when I run the netstat -an command, it only indicates whether ports are TCP or UDP. However, I have discovered that node.js differentiates between HTTP ports and TCP ports (example found at the bottom ...

Unable to continue due to being stuck in the "Starting packager" phase of React Native development

Whenever I attempt to start the React Native project (you can find it here), the npm start script gets stuck on Starting packager I have already checked these resources regarding the issue: react-community issue: 203 react-native-stuck-at-starting-packa ...

Tips for validating a field by referencing data from a different model

I'm attempting to verify the validity of a date field by cross-referencing information stored in another model within the database. During API testing, the validation appears to work correctly as it triggers the exception, but the insertion actually ...

Guide on allowing a parent module to import a sub-module within another module in NodeJS

Module X │ └─ Module Y (devDependency in Module X's package.json) │ └─ Module Z (dependency in Module Y's package.json) Module Y is the focus of my current development efforts. However, I am aware that module Z will be called w ...

Guide on utilizing PHP to display a particular value from a JSON file

Hello, I am trying to extract specific data from a JSON response. Here is the structure of the JSON: { "data":{ "user_quota":[ { "group_limit":10240, "quota":0, "support_share_quota":false, ...

Delivering numerous cfquery results to an AJAX request

I am in the process of creating a webpage that will utilize AJAX to make an API call upon submission of a webform. The AJAX call will then access a CFC (ColdFusion component) that contains a function responsible for calling a SQL stored procedure and passi ...

In what ways do node.js and libuv leverage separate threads for their operations?

During my exploration of Node.js and libuv, I decided to set up a basic node server with UV_THREADPOOL_SIZE=1. Afterward, I checked the number of threads being used by looking at pstree. For Node.js 0.10, running pstree -p | grep node resulted in: node(5 ...

Tips for executing a SOAP request using NodeJs

Despite my efforts in researching various blogs, tutorials, and videos, I still can't find a clear answer on how to execute a RESTful request. For example, in NodeJs, you would code the request, hit the route (https://localhost/3000/api/getStudent), a ...

PHP's json_encode() compared to using an empty NSDictionary in iOS development

I have a question regarding how to handle JSON encoding/decoding in PHP without converting arrays or dictionaries. In my iOS app, I store data in an NSDictionary. Some of this data is nested and includes NSArrays or other NSDictionarys that may contain fu ...

Creating a new session in Node.js for every request

Our team is currently developing a nodejs application that requires the maintenance of sessions. We have implemented express to handle node variables, but we are facing an issue where a new session is created every time we hit a new service. The structure ...

Inform the client of a "404 Not Found" Error when using the PUT method

Whenever I click the Submit button, I encounter a 404 Not Found Error when trying to call the "publish-template" endpoint. Why does this error occur even though it supposedly exists? The Pug rendering is done with the correct path for the form action: doc ...

Innovative MainMenu featuring distinct subMenus created via ng-repeat and populated with data from JSON sources

I am attempting to utilize ng-repeat to dynamically load the main menu from a JSON file. Let me explain the situation. Please refer to the provided layout screenshot for better understanding Main Menu - Groceries, Listing, Product, Blog, Gallery, Pages, ...

Unexpected problem following Ionic 2 update in Npm

Encountering an error while attempting to initiate a new app project in Ionic 2 using the following command: ionic start name blank --v2 The error message is as follows: One awesome Ionic app coming right up... Downloading: https://github.com/driftyco/ ...

The value of InlineButton should be updated in the database with the current date

I am currently working on integrating an inline button within a table that will immediately update the database with today's date when clicked. The functionality I am aiming for is to have the button "change" trigger the insertion of the current date ...