0

Folks, Trying to understand returning and forming JSON responses.

The following code returns the object as a single string:

res.send(JSON.stringify(data));

Output to the browser:

{"Count":1,"Items":[{"dbsource":{"S":"x"},"number":{"S":"5002820"},"name":{"S":"blah,foo"},"expiration":{"S":"06/13/2015"},"type":{"S":"bar"}}]}

Dont I want the JSON output to be more readable, ie :

{
"one": "two",
"key": "value"
}

What should i change JSON.stringify(data) to? Ideally I want the response to be used as an API endpoint.

Thanks!

10
  • 5
    I'd leave it alone, and then develop some sort of pretty-printer to be used by a client of the API. Commented Nov 6, 2013 at 16:17
  • 1
    I'm with Pointy. If it's only going to be an endpoint, leave it the way it is and leave the formatting to whatever client is doing the consuming. Commented Nov 6, 2013 at 16:19
  • Folks, why not labs.omniti.com/labs/jsend ? Commented Nov 6, 2013 at 16:22
  • 3
    Why not JSON.stringify(object, null, '\t')? Commented Nov 6, 2013 at 16:22
  • 1
    @Clustermagnet well the insights of LightStyle and Deepak Mishra make my point irrelevant if not plain dumb, but my thinking was that JSON is mostly for machine consumption, and isn't very human-friendly no matter how nicely it's formatted. Commented Nov 6, 2013 at 16:44

1 Answer 1

2

You are almost there. Use stringify with spaces

var str = JSON.stringify(data, undefined, 2);

The above string will have indentation with 2 spaces.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

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

2 Comments

Can you please fix the reference? 404
fixed the reference. Thanks.

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.