dopplesoldner
dopplesoldner

Reputation: 9479

Response JSON object or JSON.stringify?

Suppose I want to return JSON content

var content = {
  a: 'foo',
  b: 'bar'
};

What is the best practice to return my JSON data?

A) Return object as is; i.e res.end(content)?

B) JSON.stringify(content) and then call JSON.parse(content) on the client?

Upvotes: 8

Views: 27084

Answers (2)

Bernie
Bernie

Reputation: 5055

If you send the response with express's res.json you can send the Object directly as application/json encoded response.

app.get('/route/to/ressource', function(req, res){
  var oMyOBject = {any:'data'};

   res.json(oMyOBject);
});

Upvotes: 8

Scimonster
Scimonster

Reputation: 33409

The client must always send a string. That's what the protocol says. After all, HTTP is a wide-ranging protocol, and not all languages support JSON objects, let alone JavaScript data.

If you don't convert it to a JSON string, chances are that pure Node will just send it as [object Object], and i'm sure that's not your intention.

As mentioned previously, Express lets you send an actual JS object, and does the JSON string converting for you. Alternately, you can manually convert it.

Upvotes: 8

Related Questions