mirror of
https://github.com/httpie/cli.git
synced 2025-02-03 11:19:15 +01:00
JSON detection improvements
This commit is contained in:
parent
74e4d0b678
commit
f96f0ef9ed
@ -389,9 +389,10 @@ both of which can be overwritten:
|
|||||||
You can use ``--json, -j`` to explicitly set ``Accept``
|
You can use ``--json, -j`` to explicitly set ``Accept``
|
||||||
to ``application/json`` regardless of whether you are sending data
|
to ``application/json`` regardless of whether you are sending data
|
||||||
(it's a shortcut for setting the header via the usual header notation –
|
(it's a shortcut for setting the header via the usual header notation –
|
||||||
``http url Accept:application/json``). Also, with ``--json, -j``,
|
``http url Accept:application/json``).
|
||||||
HTTPie tries to detect if the body is JSON even if the ``Content-Type``
|
|
||||||
doesn't specify it in order to correctly format it.
|
Additionally, with the ``--json, -j`` option HTTPie tries to detect JSON
|
||||||
|
responses event when the ``Content-Type`` is ``text/plain`` or unknown.
|
||||||
|
|
||||||
Simple example:
|
Simple example:
|
||||||
|
|
||||||
|
@ -83,9 +83,8 @@ def get_lexer(mime, explicit_json=False, body=''):
|
|||||||
])
|
])
|
||||||
|
|
||||||
# As a last resort, if no lexer feels responsible, and
|
# As a last resort, if no lexer feels responsible, and
|
||||||
# the subtype contains 'json' or explicit --json is set,
|
# the subtype contains 'json', take the JSON lexer
|
||||||
# take the JSON lexer
|
if 'json' in subtype:
|
||||||
if 'json' in subtype or explicit_json:
|
|
||||||
lexer_names.append('json')
|
lexer_names.append('json')
|
||||||
|
|
||||||
# Try to resolve the right lexer.
|
# Try to resolve the right lexer.
|
||||||
@ -103,14 +102,12 @@ def get_lexer(mime, explicit_json=False, body=''):
|
|||||||
except ClassNotFound:
|
except ClassNotFound:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
if lexer and explicit_json and body and isinstance(lexer, TextLexer):
|
if explicit_json and body and (not lexer or isinstance(lexer, TextLexer)):
|
||||||
# When a text lexer is resolved even with --json (i.e. explicit
|
# JSON response with an incorrect Content-Type?
|
||||||
# text/plain Content-Type), try to parse the response as JSON
|
|
||||||
# and if it parses, sneak in the JSON lexer instead.
|
|
||||||
try:
|
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:
|
except ValueError:
|
||||||
pass # Invalid JSON, ignore.
|
pass # Nope
|
||||||
else:
|
else:
|
||||||
lexer = pygments.lexers.get_lexer_by_name('json')
|
lexer = pygments.lexers.get_lexer_by_name('json')
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user