Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Server Response to be Human-Readable

I'm doing a AJAX request to get some responses from a API, for example Twitter's API, and displaying the response to the user using highlight.js to highlight the code, but usually servers respond with less whitespace/new lines as possible, like this:

[{"in_reply_to_user_id_str":null,"contributors":null,"coordinates":null,"favorited":false,"id_str":"235118001274368000","geo":null,"user":{"id_str":"481202814","profile_background_tile":false,"id":481202814,"time_zone":"Brasilia","screen_name":"Juu_kimura","profile_sidebar_fill_color":"F6FFD1","default_profile_image":false,"location":"Paran\u00e1 ","favourites_count":2 ...

Is there any way to format this so it can be more human-readable before applying the highlight?

PS: The response can be in any format, JSON, XML, HTML, ...

like image 968
Nathan Campos Avatar asked Jan 26 '26 12:01

Nathan Campos


1 Answers

If you already parsed your response to JavaScript object:

var response = {"in_reply_to_user_id_str":null,"contributors":null,"coordinates":null,"favorited":false,"id_str":"235118001274368000"};
JSON.stringify(response, null, 4);

yields:

"{
    "in_reply_to_user_id_str": null,
    "contributors": null,
    "coordinates": null,
    "favorited": false,
    "id_str": "235118001274368000"
}"

I don't know any generic solution for XML and HTML.

See also

  • How can I pretty-print JSON in (unix) shell script?
like image 69
Tomasz Nurkiewicz Avatar answered Jan 28 '26 02:01

Tomasz Nurkiewicz