From f96f0ef9ed88b26e6609a9404b02a6a4f3be20ae Mon Sep 17 00:00:00 2001 From: Jakub Roztocil Date: Tue, 1 Mar 2016 16:22:54 +0800 Subject: [PATCH] JSON detection improvements --- README.rst | 7 ++++--- httpie/output/formatters/colors.py | 15 ++++++--------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/README.rst b/README.rst index c0055576..a55226c5 100644 --- a/README.rst +++ b/README.rst @@ -389,9 +389,10 @@ both of which can be overwritten: You can use ``--json, -j`` to explicitly set ``Accept`` to ``application/json`` regardless of whether you are sending data (it's a shortcut for setting the header via the usual header notation – -``http url Accept:application/json``). Also, with ``--json, -j``, -HTTPie tries to detect if the body is JSON even if the ``Content-Type`` -doesn't specify it in order to correctly format it. +``http url Accept:application/json``). + +Additionally, with the ``--json, -j`` option HTTPie tries to detect JSON +responses event when the ``Content-Type`` is ``text/plain`` or unknown. Simple example: diff --git a/httpie/output/formatters/colors.py b/httpie/output/formatters/colors.py index 10ce5db2..43a28829 100644 --- a/httpie/output/formatters/colors.py +++ b/httpie/output/formatters/colors.py @@ -83,9 +83,8 @@ def get_lexer(mime, explicit_json=False, body=''): ]) # As a last resort, if no lexer feels responsible, and - # the subtype contains 'json' or explicit --json is set, - # take the JSON lexer - if 'json' in subtype or explicit_json: + # the subtype contains 'json', take the JSON lexer + if 'json' in subtype: lexer_names.append('json') # Try to resolve the right lexer. @@ -103,14 +102,12 @@ def get_lexer(mime, explicit_json=False, body=''): except ClassNotFound: pass - if lexer and explicit_json and body and isinstance(lexer, TextLexer): - # When a text lexer is resolved even with --json (i.e. explicit - # text/plain Content-Type), try to parse the response as JSON - # and if it parses, sneak in the JSON lexer instead. + if explicit_json and body and (not lexer or isinstance(lexer, TextLexer)): + # JSON response with an incorrect Content-Type? try: - json.loads(body) # FIXME: it also gets parsed in json.py + json.loads(body) # FIXME: the body also gets parsed in json.py except ValueError: - pass # Invalid JSON, ignore. + pass # Nope else: lexer = pygments.lexers.get_lexer_by_name('json')