Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

285
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda