How can I tell Apigee Edge to emit a "pretty printed" JSON payload?

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';     

Is there a better way?

Solved Solved
1 3 1,505
1 ACCEPTED SOLUTION

Not applicable

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.

View solution in original post

3 REPLIES 3

Not applicable

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.

Just to add my two cents to @Michael Russo's response:

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.

Thanks, guys!