2014-04-27 00:07:13 +02:00
|
|
|
from __future__ import absolute_import
|
|
|
|
import json
|
|
|
|
|
2014-04-28 23:33:30 +02:00
|
|
|
from httpie.plugins import FormatterPlugin
|
2014-04-27 00:07:13 +02:00
|
|
|
|
|
|
|
|
2014-04-28 23:33:30 +02:00
|
|
|
DEFAULT_INDENT = 4
|
2014-04-27 00:07:13 +02:00
|
|
|
|
2014-04-28 23:33:30 +02:00
|
|
|
|
|
|
|
class JSONFormatter(FormatterPlugin):
|
|
|
|
|
|
|
|
def format_body(self, body, mime):
|
2016-03-01 07:57:15 +01:00
|
|
|
if 'json' in mime or self.kwargs['explicit_json']:
|
2014-04-27 00:07:13 +02:00
|
|
|
try:
|
|
|
|
obj = json.loads(body)
|
|
|
|
except ValueError:
|
2016-03-01 07:57:15 +01:00
|
|
|
pass # Invalid JSON, ignore.
|
2014-04-27 00:07:13 +02:00
|
|
|
else:
|
|
|
|
# Indent, sort keys by name, and avoid
|
|
|
|
# unicode escapes to improve readability.
|
2016-03-01 07:57:15 +01:00
|
|
|
body = json.dumps(
|
|
|
|
obj=obj,
|
|
|
|
sort_keys=True,
|
|
|
|
ensure_ascii=False,
|
|
|
|
indent=DEFAULT_INDENT
|
|
|
|
)
|
2014-04-27 00:07:13 +02:00
|
|
|
return body
|