8

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?

0

2 Answers 2

8

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Yes I am aware of that functionality. However I just wanted to know what are the pros and cons? Why would one prefer to convert into string or the other way round?
@dopplesoldner In fact, res.send() has already done the stringify works, whatever you did, client will always receives the JSON formatted data.
You don't need to set the type because .send will do it for you, and you can do app.set('json spaces', '\t') if you want formatted output.
8

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.

2 Comments

So if I understand correctly, the protocol is to always send a string instead of an object? And res.json() does the conversion internally? Also if I am sending a string from the server, I will require JSON.parse(data) on the browser?
Yes. If you use jQuery's $.getJSON() method, it does the JSON.parse() internally also.

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.