Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

282
Views
Node API function returning array of strings instead of objects

I'd like to return an array of JSON objects from this function but I'm having issues with the formatting. I'm new to Node.js and hoping to understand it better.

function getItems (callback) {
  connection.query(SQL_getItems, (err, results) => {
    if (err) {
      callback(err);
      return;
    }
    callback(null, results.map((item) => `{'name': '${item.name}', 'value': '${item.value}'}`));
  });
}

The current JSON looks like this:

["name: test, value: 1","name: test2, value: 0"]

What I want is an array of JSON objects

[{"name": "test","value": "1"},{"name": "test2","value": "0"}]

I've tried tweaking the formatting, but can't get it quite right. I tried JSON.parse but it's already valid (but not ideal) JSON.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Actually, with using template string like this:

`{'name': '${item.name}', 'count': '${item.value}'}`

the map function will return an array of string, that is what you've got. To return an JSON object as expected, I think your code should be:

results.map(item => JSON.stringify({name: item.name, count: item.value}))

p/s: If I remember exactly, you can pass the accept header as application/json to get your work done automatically with res.send({<JS object>}).

UPDATED: Does your result looks like this, I tried but get diffrent result from yours:

enter image description here

about 4 years ago · Santiago Trujillo Report

0

Thanks to @thelonglqd for pointing me in the right direction. The issue was that the results were already in the format I needed, so I was double encoding them.

function getItems (callback) {
  connection.query(SQL_getItems, (err, results) => {
    if (err) {
      callback(err);
      return;
    }
    callback(null, JSON.stringify(results));
  });
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!