httpie-cli/httpie/output/formatters/json.py
Jakub Roztocil 7917f1b40c Build fixes and clean-up
* reflect Python 3.7 release
* fix `pycodestyle` errors
* update `pycodestyle` config
* move `pytest` and `pycodestyle` config to `setup.cfg`
* add `make pycodestyle`
* add `make coveralls`
* etc.
2018-07-12 21:16:16 +02:00

34 lines
884 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):
maybe_json = [
'json',
'javascript',
'text',
]
if (self.kwargs['explicit_json']
or any(token in mime for token in maybe_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