From 86db08793bd4f176f0d6d4c19cf7ad17cd4312ac Mon Sep 17 00:00:00 2001 From: Markus Heiser Date: Sun, 18 Jun 2023 18:14:46 +0200 Subject: [PATCH] [fix] implement a JSONEncoder for the json format This patch implements a simple JSONEncoder just to fix #2502 / on the long term SearXNG needs a data schema for the result items and a json generator for the result list. Closes: https://github.com/searxng/searxng/issues/2505 Signed-off-by: Markus Heiser --- searx/webutils.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/searx/webutils.py b/searx/webutils.py index ddd9891bf..bfc6b22f7 100644 --- a/searx/webutils.py +++ b/searx/webutils.py @@ -143,6 +143,17 @@ def write_csv_response(csv: CSVWriter, rc: ResultContainer) -> None: csv.writerow([row.get(key, '') for key in keys]) +class JSONEncoder(json.JSONEncoder): + def default(self, o): + if isinstance(o, datetime): + return o.isoformat() + if isinstance(o, timedelta): + return o.total_seconds() + if isinstance(o, set): + return list(o) + return super().default(o) + + def get_json_response(sq: SearchQuery, rc: ResultContainer) -> str: """Returns the JSON string of the results to a query (``application/json``)""" results = rc.number_of_results @@ -156,7 +167,7 @@ def get_json_response(sq: SearchQuery, rc: ResultContainer) -> str: 'suggestions': list(rc.suggestions), 'unresponsive_engines': get_translated_errors(rc.unresponsive_engines), } - response = json.dumps(x, default=lambda item: list(item) if isinstance(item, set) else item) + response = json.dumps(x, cls=JSONEncoder) return response