0

I am new to Express and I wonder whether I can parse some property before sending the response to the frontend. The response would be an array of objects. In each object there are properties that includes JSON objects which are stringified. I want to parse them before sending them to the frontend.

Would I iterate through the response and use JSON.parse() on all properties which are stringified in the backend or would I have to handle them in my frontend?

Here is my code:

  router.get('/posts', function (req, res) {
    db.query(
      'select * from posts;',
      [10*(req.params.page || 0)],
      (error, results) => {
        if (error) {
          console.log(error);
          res.status(500).json({status: 'error'});
        } else {
          res.status(200).json(results);
        }
      }
    );
  });

1 Answer 1

1

Example given below Parsing a file containing JSON data.But you can use as per your requirement on your result set.

Asynchronous version

var fs = require('fs');

fs.readFile('/path/to/file.json', 'utf8', function (err, data) {
    if (err) throw err; // we'll not consider error handling for now
    var obj = JSON.parse(data);
});

Synchronous version

var fs = require('fs');
var json = JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8'));

OR

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);

Hope this will help you to parse your result set to JSON.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.