Suppose I have an Apigee Edge proxy that returns JSON. That JSON may be returned from some back-end service, or it may be generated by… something like a OAuthV2-GenerateAccessToken, or even a XMLToJSON policy. But I want the resulting JSON to be pretty-printed. What’s the best way to accomplish that?
I can think of one way: Use a Javascript step in the response flow that does something like this:
var payload = JSON.parse(response.content);
response.content = JSON.stringify(payload,null,2) + '\n';
I’ve always used the JSON.stringify options to set the pretty printing if needed. Works well.
However, clients should be left to do the pretty printing (example Postman) or the server should only do this when developing/debugging. In production, compact JSON data should be used without the tabs, newlines, etc. to save on space for data transfer as humans aren’t reading the responses anyways.
JSON.stringify(payload, null, true) is the code that will return pretty-printed JSON.
And Michael is completely correct about returning JSON – pretty-printed JSON should not be returned from APIs. Pretty-printed JSON is in fact not valid JSON. Many APIs will handle pretty printed JSON correctly, but you should probably return valid JSON from your API and let the client pretty print it if desired.