Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

289
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda