Skip to content

Instantly share code, notes, and snippets.

@dukebody
Last active March 28, 2024 11:44
Show Gist options
  • Save dukebody/dcc371bf286534d546e9 to your computer and use it in GitHub Desktop.
Save dukebody/dcc371bf286534d546e9 to your computer and use it in GitHub Desktop.
JSON field for WTForms that converts between the form string data and a dictionary representation, with validation
from wtforms import fields
import json
class JSONField(fields.StringField):
def _value(self):
return json.dumps(self.data) if self.data else ''
def process_formdata(self, valuelist):
if valuelist:
try:
self.data = json.loads(valuelist[0])
except ValueError:
raise ValueError('This field contains invalid JSON')
else:
self.data = None
def pre_validate(self, form):
super().pre_validate(form)
if self.data:
try:
json.dumps(self.data)
except TypeError:
raise ValueError('This field contains invalid JSON')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment