Skip to content

Commit

Permalink
[#1078] 2.7 comatibility fix: use simplejson for lazyjson
Browse files Browse the repository at this point in the history
  • Loading branch information
wardi committed Sep 4, 2013
1 parent 12420ce commit 5f0ca73
Showing 1 changed file with 57 additions and 4 deletions.
61 changes: 57 additions & 4 deletions ckan/lib/lazyjson.py
@@ -1,4 +1,5 @@
import json
import simplejson as json
import simplejson.encoder as json_encoder


class LazyJSONObject(object):
Expand Down Expand Up @@ -35,9 +36,61 @@ def method(self, *args, **kwargs):
setattr(LazyJSONObject, fn, _loads_method(fn))


class JSONString(str):
'''a type for already-encoded JSON'''
pass


def _encode_jsonstring(s):
if isinstance(s, JSONString):
return s
return json_encoder.encode_basestring(s)


class LazyJSONEncoder(json.JSONEncoder):
'''JSON encoder that handles LazyJSONObject elements'''
def _iterencode_default(self, o, markers=None):
def iterencode(self, o, _one_shot=False):
'''
most of JSONEncoder.iterencode() copied so that _encode_jsonstring
may be used instead of encode_basestring
'''
if self.check_circular:
markers = {}
else:
markers = None
def floatstr(o, allow_nan=self.allow_nan,
_repr=json_encoder.FLOAT_REPR,
_inf=json_encoder.PosInf,
_neginf=-json_encoder.PosInf):
# Check for specials. Note that this type of test is processor
# and/or platform-specific, so do tests which don't depend on the
# internals.

if o != o:
text = 'NaN'
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return _repr(o)

if not allow_nan:
raise ValueError(
"Out of range float values are not JSON compliant: " +
repr(o))

return text
_iterencode = json_encoder._make_iterencode(
markers, self.default, _encode_jsonstring, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot, self.use_decimal,
self.namedtuple_as_object, self.tuple_as_array,
self.bigint_as_string, self.item_sort_key,
self.encoding, Decimal=json_encoder.Decimal)
return _iterencode(o, 0)

def default(self, o):
if hasattr(o, 'to_json_string'):
return iter([o.to_json_string()])
return json.JSONEncoder._iterencode_default(self, o, markers)
return JSONString(o.to_json_string())
return json.JSONEncoder.default(self, o)

0 comments on commit 5f0ca73

Please sign in to comment.