forked from extern/httpie-cli
74e4d0b678
To correctly format JSON responses even when an incorrect ``Content-Type`` is returned. Closes #92 Closes #349 Closes #368
28 lines
739 B
Python
28 lines
739 B
Python
from __future__ import absolute_import
|
|
import json
|
|
|
|
from httpie.plugins import FormatterPlugin
|
|
|
|
|
|
DEFAULT_INDENT = 4
|
|
|
|
|
|
class JSONFormatter(FormatterPlugin):
|
|
|
|
def format_body(self, body, mime):
|
|
if 'json' in mime or self.kwargs['explicit_json']:
|
|
try:
|
|
obj = json.loads(body)
|
|
except ValueError:
|
|
pass # Invalid JSON, ignore.
|
|
else:
|
|
# Indent, sort keys by name, and avoid
|
|
# unicode escapes to improve readability.
|
|
body = json.dumps(
|
|
obj=obj,
|
|
sort_keys=True,
|
|
ensure_ascii=False,
|
|
indent=DEFAULT_INDENT
|
|
)
|
|
return body
|