Skip to content

Commit

Permalink
check if the string is already valid JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
dantownsend committed Oct 25, 2024
1 parent ac6d14f commit 39bab6c
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions piccolo/query/operators/json.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from __future__ import annotations

import json
import typing as t

from piccolo.querystring import QueryString
from piccolo.utils.encoding import dump_json
from piccolo.utils.encoding import dump_json, load_json

if t.TYPE_CHECKING:
from piccolo.columns.column_types import JSON
Expand All @@ -12,9 +13,18 @@
class JSONQueryString(QueryString):

def clean_value(self, value: t.Any):
if not isinstance(value, QueryString):
value = dump_json(value)
return value
if isinstance(value, QueryString):
return value
elif isinstance(value, str):
# The string might already be valid JSON, in which case, leave it.
try:
load_json(value)
except json.JSONDecodeError:
pass
else:
return value

return dump_json(value)

def __eq__(self, value) -> QueryString: # type: ignore[override]
value = self.clean_value(value)
Expand Down

0 comments on commit 39bab6c

Please sign in to comment.