How to respond with a JSON object in Node.js and Express?

Sometimes, we want to respond with a JSON object in Node.js and Express.

In this article, we’ll look at how to respond with a JSON object in Node.js and Express.

How to respond with a JSON object in Node.js and Express?

To respond with a JSON object in Node.js and Express, we can call the res.json method.

For instance, we add

res.json({
  anObject: {
    item1: "item1val",
    item2: "item2val"
  },
  anArray: ["item1", "item2"],
  another: "item"
});

in our route handler function to respond with

{
  anObject: {
    item1: "item1val",
    item2: "item2val"
  },
  anArray: ["item1", "item2"],
  another: "item"
}

res.json takes any plain JavaScript object and return it as a JSON string response.

Conclusion

To respond with a JSON object in Node.js and Express, we can call the res.json method.