diff options
author | Kevin LaFlamme <kevin@lolatravel.com> | 2016-09-01 12:26:43 -0400 |
---|---|---|
committer | Kevin LaFlamme <kevin@lolatravel.com> | 2016-09-01 12:26:43 -0400 |
commit | da17e3529c4e41173519ea18ff3ee908761ef5d4 (patch) | |
tree | e987a357593f5184b45cd8482ba544b5a8d66978 /simplejson/encoder.py | |
parent | 4b1dab370f8a32aaa3f9140c38645093d3287b82 (diff) | |
download | simplejson-da17e3529c4e41173519ea18ff3ee908761ef5d4.tar.gz |
Add support for preprocessed JSON strings (with optimizations) in encoder
In some situations, you may have a large python dictionary you need to JSONify but one of the values inside the dict is already a JSON string. This is common when pulling an object from a database, for example, where one of the fields is a JSON blob/string. Previously you would have to deserialize and then reserialize that string just to serialize the high level object, but obviously this is unnecessarily slow. This changes adds a method/type that can be used to wrap a str and tell the serializer to just pass it through instead.
Diffstat (limited to 'simplejson/encoder.py')
-rw-r--r-- | simplejson/encoder.py | 10 |
1 files changed, 10 insertions, 0 deletions
diff --git a/simplejson/encoder.py b/simplejson/encoder.py index 5b9bda7..9a4c0c5 100644 --- a/simplejson/encoder.py +++ b/simplejson/encoder.py @@ -39,6 +39,10 @@ for i in [0x2028, 0x2029]: FLOAT_REPR = repr +class RawJSON(object): + def __init__(self, encoded_json): + self.encoded_json = encoded_json + def encode_basestring(s, _PY3=PY3, _q=u('"')): """Return a JSON representation of a Python string @@ -464,6 +468,8 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, if (isinstance(value, string_types) or (_PY3 and isinstance(value, binary_type))): yield buf + _encoder(value) + elif isinstance(value, RawJSON): + yield buf + value.encoded_json elif value is None: yield buf + 'null' elif value is True: @@ -582,6 +588,8 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, if (isinstance(value, string_types) or (_PY3 and isinstance(value, binary_type))): yield _encoder(value) + elif isinstance(value, RawJSON): + yield value.encoded_json elif value is None: yield 'null' elif value is True: @@ -624,6 +632,8 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, if (isinstance(o, string_types) or (_PY3 and isinstance(o, binary_type))): yield _encoder(o) + elif isinstance(o, RawJSON): + buf + o.encoded_json elif o is None: yield 'null' elif o is True: |