Httpie: Pretty Print JSON Body

Created on 13 Nov 2015  ·  6Comments  ·  Source: httpie/httpie

How to pretty print a JSON output body in order to format it in bash console like

macbookproloreto:~ admin$ echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool
{
    "bar": "ipsum",
    "foo": "lorem"
}

My command looks like now

http --session=cookies.txt --pretty all --json --print=b --style=xcode "https://myapi.company.com | python -m json.tool

Does the option --pretty aims to pretty print the output body? Having it seems to not prettify the output body, instead it prints the json as plain text

'{"foo": "lorem", "bar": "ipsum"}'

Most helpful comment

@jkbrzt exactly. In fact the issue was that the server headers was text/plain while the body was a text formatted as a json body (well formatted json). Basically the response header Content-Type is not application/json. Can HTTPie force json formatting in those cases?

All 6 comments

This works out of the box:

screen shot 2016-01-01 at 6 58 34 pm

@jkbrzt yes but this is not the response body. It seems it does not pretty the body but only the headers.

@loretoparisi it is the response body, see http://httpbin.org/get

Ok I have found the issue, it's something wrong in the response headers. In fact if I try a well formatted response body with json format like:

http --session=cookies.txt --pretty all --json --print=b --style=xcode "https://api.spotify.com/v1/tracks/0eGsygTp906u18L0Oimnem"

it works.
When the http response headers are text/plain

HTTP/1.1 200 OK
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 1996
Content-Type: text/plain; charset=utf-8

the resulting formatting is plain.

HTTPie looks at the response Content-Type header. If it's text/plain, then it doesn't do any special formatting. The URL you provided returns Content-Type: application/json; charset=utf-8 so it gets properly formatted and highlighted as JSON.

screen shot 2016-01-03 at 6 58 33 pm

@jkbrzt exactly. In fact the issue was that the server headers was text/plain while the body was a text formatted as a json body (well formatted json). Basically the response header Content-Type is not application/json. Can HTTPie force json formatting in those cases?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

maciej picture maciej  ·  4Comments

Govinda-Fichtner picture Govinda-Fichtner  ·  6Comments

jclem picture jclem  ·  6Comments

eliangcs picture eliangcs  ·  5Comments

chuma picture chuma  ·  3Comments