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
|
|
|
class JSONFormatter(FormatterPlugin):
|
|
|
|
|
2020-05-27 15:58:15 +02:00
|
|
|
def __init__(self, **kwargs):
|
|
|
|
super().__init__(**kwargs)
|
|
|
|
self.enabled = self.format_options['json']['format']
|
|
|
|
|
2019-08-31 19:11:46 +02:00
|
|
|
def format_body(self, body: str, mime: str) -> str:
|
2016-07-01 18:57:13 +02:00
|
|
|
maybe_json = [
|
|
|
|
'json',
|
|
|
|
'javascript',
|
|
|
|
'text',
|
|
|
|
]
|
2018-07-12 21:16:16 +02:00
|
|
|
if (self.kwargs['explicit_json']
|
|
|
|
or any(token in mime for token in maybe_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,
|
2020-05-27 15:58:15 +02:00
|
|
|
sort_keys=self.format_options['json']['sort_keys'],
|
2016-03-01 07:57:15 +01:00
|
|
|
ensure_ascii=False,
|
2020-05-27 15:58:15 +02:00
|
|
|
indent=self.format_options['json']['indent']
|
2016-03-01 07:57:15 +01:00
|
|
|
)
|
2014-04-27 00:07:13 +02:00
|
|
|
return body
|