2014-04-27 00:07:13 +02:00
|
|
|
import json
|
|
|
|
|
2021-05-05 14:13:39 +02:00
|
|
|
from ...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)):
|
2021-09-21 11:15:43 +02:00
|
|
|
from ..utils import load_prefixed_json
|
2014-04-27 00:07:13 +02:00
|
|
|
try:
|
2021-09-21 11:15:43 +02:00
|
|
|
data_prefix, json_obj = load_prefixed_json(body)
|
2014-04-27 00:07:13 +02:00
|
|
|
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.
|
2021-09-21 11:15:43 +02:00
|
|
|
body = data_prefix + json.dumps(
|
|
|
|
obj=json_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
|