Skip to content

Commit

Permalink
Refs #7 - Fix JSONField with default values saved to XML (#8)
Browse files Browse the repository at this point in the history
Refs #7 - Fix JSONField with default values saved to  XML
  • Loading branch information
avoinea committed Apr 2, 2020
1 parent e44aff1 commit 1669a65
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 6 deletions.
2 changes: 2 additions & 0 deletions news/7.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix JSONField with default values saved to `model_source` XML
[avoinea]
29 changes: 26 additions & 3 deletions plone/schema/jsonfield.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import ast
import json
import jsonschema
from plone.schema import _
from zope.interface import Attribute
from zope.interface import implementer
Expand All @@ -7,8 +10,11 @@
from zope.schema.interfaces import WrongContainedType
from zope.schema.interfaces import IFromUnicode

import json
import jsonschema
try:
from json import JSONDecodeError
except ImportError:
# Python 2
JSONDecodeError = ValueError


DEFAULT_JSON_SCHEMA = json.dumps({
Expand Down Expand Up @@ -48,6 +54,23 @@ def _validate(self, value):
raise WrongContainedType(e.message, self.__name__)

def fromUnicode(self, value):
v = json.loads(value)
""" Get value from unicode.
Value can be a valid JSON object:
>>> JSONField().fromUnicode('{"items": []}')
{'items': []}
or it can be a Pyhon dict stored as string:
>>> JSONField().fromUnicode("{'items': []}")
{'items': []}
"""
try:
v = json.loads(value)
except JSONDecodeError:
v = ast.literal_eval(value)

self.validate(v)
return v
2 changes: 2 additions & 0 deletions plone/schema/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
""" Tests
"""
23 changes: 23 additions & 0 deletions plone/schema/tests/test_doctests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
""" Tests
"""
import re
import six
import unittest
import doctest

class Py23DocChecker(doctest.OutputChecker):
def check_output(self, want, got, optionflags):
if six.PY2:
got = re.sub("u'(.*?)'", "'\\1'", want)
got = re.sub(' encoding="utf-8"', '', want)
# want = re.sub("b'(.*?)'", "'\\1'", want)
return doctest.OutputChecker.check_output(self, want, got, optionflags)


def test_suite():
return unittest.TestSuite((
doctest.DocTestSuite(
'plone.schema.jsonfield',
checker=Py23DocChecker()
),
))
7 changes: 4 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@
'zope.interface',
'zope.schema',
],
extras_require={
'test': ['plone.app.testing'],
},
extras_require={'test': [
'six',
'plone.app.testing'
]},
)

0 comments on commit 1669a65

Please sign in to comment.