beachCode
beachCode

Reputation: 3510

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.

Upvotes: 0

Views: 678

Answers (2)

beachCode
beachCode

Reputation: 3510

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));
  });
}

Upvotes: 0

thelonglqd
thelonglqd

Reputation: 1862

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

Upvotes: 1

Related Questions