Solved Solved

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

DChiesa
Staff

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,030
1 ACCEPTED SOLUTION
Solved Solved

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

Solved Solved
2 0 0
3 REPLIES 3
Solved Solved

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

Solved Solved
2 0 1

mdunker
Staff

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.

1 0 0

DChiesa
Staff

Thanks, guys!

0 0 0
Top Labels in this Space
Top Solution Authors