summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorScott Maxwell <scott@codecobblers.com>2012-03-01 23:25:25 -0800
committerScott Maxwell <scott@codecobblers.com>2012-03-01 23:25:25 -0800
commit08ef2e3e6e7da0fe9a5d2c73bbcc947489808579 (patch)
tree16ddea60cb8b87a297f5548731e94a6d180322de
parent9069fbfe3d856e4b66b42c9a354423812e5a593b (diff)
downloadsimplejson-08ef2e3e6e7da0fe9a5d2c73bbcc947489808579.tar.gz
Added javascript_safe_ints support
Javascript cannot display integers of 2^54 or higher without loss of precision. This option will put numbers of 2^54 and higher or -2^54 and lower into quotes.
-rw-r--r--simplejson/__init__.py15
-rw-r--r--simplejson/_speedups.c31
-rw-r--r--simplejson/encoder.py19
3 files changed, 51 insertions, 14 deletions
diff --git a/simplejson/__init__.py b/simplejson/__init__.py
index 3ee7893..719f345 100644
--- a/simplejson/__init__.py
+++ b/simplejson/__init__.py
@@ -138,12 +138,13 @@ _default_encoder = JSONEncoder(
use_decimal=True,
namedtuple_as_object=True,
tuple_as_array=True,
+ javascript_safe_ints=False
)
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, use_decimal=True,
- namedtuple_as_object=True, tuple_as_array=True,
+ namedtuple_as_object=True, tuple_as_array=True, javascript_safe_ints=False,
**kw):
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
@@ -193,6 +194,10 @@ def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
If *tuple_as_array* is true (default: ``True``),
:class:`tuple` (and subclasses) will be encoded as JSON arrays.
+ If javascript_safe_ints is true (not the default), ints 2**54 and higher
+ or -2**54 and lower will be encoded as strings. This is to avoid the
+ rounding that happens in Javascript otherwise.
+
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
@@ -214,6 +219,7 @@ def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
default=default, use_decimal=use_decimal,
namedtuple_as_object=namedtuple_as_object,
tuple_as_array=tuple_as_array,
+ javascript_safe_ints=javascript_safe_ints,
**kw).iterencode(obj)
# could accelerate with writelines in some versions of Python, at
# a debuggability cost
@@ -225,7 +231,7 @@ def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, use_decimal=True,
namedtuple_as_object=True,
- tuple_as_array=True,
+ tuple_as_array=True, javascript_safe_ints=False,
**kw):
"""Serialize ``obj`` to a JSON formatted ``str``.
@@ -272,6 +278,10 @@ def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
If *tuple_as_array* is true (default: ``True``),
:class:`tuple` (and subclasses) will be encoded as JSON arrays.
+ If javascript_safe_ints is true (not the default), ints 2**54 and higher
+ or -2**54 and lower will be encoded as strings. This is to avoid the
+ rounding that happens in Javascript otherwise.
+
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
@@ -293,6 +303,7 @@ def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
use_decimal=use_decimal,
namedtuple_as_object=namedtuple_as_object,
tuple_as_array=tuple_as_array,
+ javascript_safe_ints=javascript_safe_ints,
**kw).encode(obj)
diff --git a/simplejson/_speedups.c b/simplejson/_speedups.c
index c25909e..c2a1ec4 100644
--- a/simplejson/_speedups.c
+++ b/simplejson/_speedups.c
@@ -89,6 +89,7 @@ typedef struct _PyEncoderObject {
int use_decimal;
int namedtuple_as_object;
int tuple_as_array;
+ int javascript_safe_ints;
} PyEncoderObject;
static PyMemberDef encoder_members[] = {
@@ -2025,19 +2026,19 @@ static int
encoder_init(PyObject *self, PyObject *args, PyObject *kwds)
{
/* initialize Encoder object */
- static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", "key_memo", "use_decimal", "namedtuple_as_object", "tuple_as_array", NULL};
+ static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", "key_memo", "use_decimal", "namedtuple_as_object", "tuple_as_array", "javascript_safe_ints", NULL};
PyEncoderObject *s;
PyObject *markers, *defaultfn, *encoder, *indent, *key_separator;
- PyObject *item_separator, *sort_keys, *skipkeys, *allow_nan, *key_memo, *use_decimal, *namedtuple_as_object, *tuple_as_array;
+ PyObject *item_separator, *sort_keys, *skipkeys, *allow_nan, *key_memo, *use_decimal, *namedtuple_as_object, *tuple_as_array, *javascript_safe_ints;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOOOOOO:make_encoder", kwlist,
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOOOOOOO:make_encoder", kwlist,
&markers, &defaultfn, &encoder, &indent, &key_separator, &item_separator,
&sort_keys, &skipkeys, &allow_nan, &key_memo, &use_decimal,
- &namedtuple_as_object, &tuple_as_array))
+ &namedtuple_as_object, &tuple_as_array, &javascript_safe_ints))
return -1;
s->markers = markers;
@@ -2054,6 +2055,7 @@ encoder_init(PyObject *self, PyObject *args, PyObject *kwds)
s->use_decimal = PyObject_IsTrue(use_decimal);
s->namedtuple_as_object = PyObject_IsTrue(namedtuple_as_object);
s->tuple_as_array = PyObject_IsTrue(tuple_as_array);
+ s->javascript_safe_ints = PyObject_IsTrue(javascript_safe_ints);
Py_INCREF(s->markers);
Py_INCREF(s->defaultfn);
@@ -2189,8 +2191,18 @@ encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssi
}
else if (PyInt_Check(obj) || PyLong_Check(obj)) {
PyObject *encoded = PyObject_Str(obj);
- if (encoded != NULL)
+ if (encoded != NULL) {
+ if (s->javascript_safe_ints) {
+ int overflow;
+ PY_LONG_LONG value = PyLong_AsLongLongAndOverflow(obj, &overflow);
+ if (overflow || (value>0 && (value>>54)) || (value<0 && ((-value)>>54))) {
+ PyObject* quoted = PyString_FromFormat("\"%s\"", PyString_AsString(encoded));
+ Py_DECREF(encoded);
+ encoded = quoted;
+ }
+ }
rv = _steal_list_append(rval, encoded);
+ }
}
else if (PyFloat_Check(obj)) {
PyObject *encoded = encoder_encode_float(s, obj);
@@ -2395,6 +2407,15 @@ encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ss
kstr = PyObject_Str(key);
if (kstr == NULL)
goto bail;
+ if (s->javascript_safe_ints) {
+ int overflow;
+ PY_LONG_LONG value = PyLong_AsLongLongAndOverflow(kstr, &overflow);
+ if (overflow || (value>0 && (value>>54)) || (value<0 && ((-value)>>54))) {
+ PyObject* quoted = PyString_FromFormat("\"%s\"", PyString_AsString(kstr));
+ Py_DECREF(kstr);
+ kstr = quoted;
+ }
+ }
}
else if (skipkeys) {
Py_DECREF(item);
diff --git a/simplejson/encoder.py b/simplejson/encoder.py
index 7f4f1cb..2ca80d0 100644
--- a/simplejson/encoder.py
+++ b/simplejson/encoder.py
@@ -107,7 +107,7 @@ class JSONEncoder(object):
check_circular=True, allow_nan=True, sort_keys=False,
indent=None, separators=None, encoding='utf-8', default=None,
use_decimal=True, namedtuple_as_object=True,
- tuple_as_array=True):
+ tuple_as_array=True, javascript_safe_ints=False):
"""Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
@@ -160,6 +160,10 @@ class JSONEncoder(object):
If tuple_as_array is true (the default), tuple (and subclasses) will
be encoded as JSON arrays.
+
+ If javascript_safe_ints is true (not the default), ints 2**54 and higher
+ or -2**54 and lower will be encoded as strings. This is to avoid the
+ rounding that happens in Javascript otherwise.
"""
self.skipkeys = skipkeys
@@ -170,6 +174,7 @@ class JSONEncoder(object):
self.use_decimal = use_decimal
self.namedtuple_as_object = namedtuple_as_object
self.tuple_as_array = tuple_as_array
+ self.javascript_safe_ints = javascript_safe_ints
if indent is not None and not isinstance(indent, basestring):
indent = indent * ' '
self.indent = indent
@@ -285,13 +290,13 @@ class JSONEncoder(object):
markers, self.default, _encoder, self.indent,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, self.allow_nan, key_memo, self.use_decimal,
- self.namedtuple_as_object, self.tuple_as_array)
+ self.namedtuple_as_object, self.tuple_as_array, self.javascript_safe_ints)
else:
_iterencode = _make_iterencode(
markers, self.default, _encoder, 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.namedtuple_as_object, self.tuple_as_array, self.javascript_safe_ints)
try:
return _iterencode(o, 0)
finally:
@@ -327,7 +332,7 @@ class JSONEncoderForHTML(JSONEncoder):
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
_key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
- _use_decimal, _namedtuple_as_object, _tuple_as_array,
+ _use_decimal, _namedtuple_as_object, _tuple_as_array, _javascript_safe_ints,
## HACK: hand-optimized bytecode; turn globals into locals
False=False,
True=True,
@@ -378,7 +383,7 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
elif value is False:
yield buf + 'false'
elif isinstance(value, (int, long)):
- yield buf + str(value)
+ yield buf + str(value) if not _javascript_safe_ints or -2**54<value<2**54 else buf + '"' + str(value) + '"'
elif isinstance(value, float):
yield buf + _floatstr(value)
elif _use_decimal and isinstance(value, Decimal):
@@ -465,7 +470,7 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
elif value is False:
yield 'false'
elif isinstance(value, (int, long)):
- yield str(value)
+ yield str(value) if not _javascript_safe_ints or -2**54<value<2**54 else '"' + str(value) + '"'
elif isinstance(value, float):
yield _floatstr(value)
elif _use_decimal and isinstance(value, Decimal):
@@ -503,7 +508,7 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
elif o is False:
yield 'false'
elif isinstance(o, (int, long)):
- yield str(o)
+ yield str(o) if not _javascript_safe_ints or -2**54<value<2**54 else '"' + str(o) + '"'
elif isinstance(o, float):
yield _floatstr(o)
elif isinstance(o, list):