How to use the simplejson.encoder.JSONEncoder function in simplejson

To help you get started, we’ve selected a few simplejson examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github google / personfinder / app / main.py View on Github external
if request.get('operation') == 'setup_datastore':
                setup_pf.setup_datastore()
                self.redirect(env.global_url + '/')
                return
            else:
                get_vars = lambda: {'env': env}
                content = resources.get_rendered('setup_datastore.html', env.lang,
                        (env.repo, env.charset), get_vars)
                response.out.write(content)

        if env.config.get('enable_react_ui') and self.should_serve_react_ui():
            csp_nonce = self.set_content_security_policy()
            react_env = {
                'maps_api_key': env.config.get('maps_api_key'),
            }
            json_encoder = simplejson.encoder.JSONEncoder()
            response.out.write(
                resources.get_rendered(
                    'react_index.html', env.lang,
                    get_vars=lambda: {
                        'env': env,
                        'csp_nonce': csp_nonce,
                        'env_json': json_encoder.encode(react_env),
                    }))
            return

        if env.action in HANDLER_CLASSES:
            # Dispatch to the handler for the specified action.
            module_name, class_name = HANDLER_CLASSES[env.action].split('.')
            handler = getattr(__import__(module_name), class_name)(
                request, response, env)
            getattr(handler, request.method.lower())()  # get() or post()
github dzhibas / SublimePrettyJson / simplejson / __init__.py View on Github external
enc.py_encode_basestring_ascii)
        scan.make_scanner = scan.c_make_scanner or scan.py_make_scanner
    else:
        dec.scanstring = dec.py_scanstring
        enc.c_make_encoder = None
        enc.encode_basestring_ascii = enc.py_encode_basestring_ascii
        scan.make_scanner = scan.py_make_scanner
    dec.make_scanner = scan.make_scanner
    global _default_decoder
    _default_decoder = JSONDecoder(
        encoding=None,
        object_hook=None,
        object_pairs_hook=None,
    )
    global _default_encoder
    _default_encoder = JSONEncoder(
       skipkeys=False,
       ensure_ascii=True,
       check_circular=True,
       allow_nan=True,
       indent=None,
       separators=None,
       encoding='utf-8',
       default=None,
   )
github simplejson / simplejson / simplejson / __init__.py View on Github external
"""
    # cached encoder
    if (not skipkeys and ensure_ascii and
        check_circular and allow_nan and
        cls is None and indent is None and separators is None and
        encoding == 'utf-8' and default is None and use_decimal
        and namedtuple_as_object and tuple_as_array and not iterable_as_array
        and not bigint_as_string and not sort_keys
        and not item_sort_key and not for_json
        and not ignore_nan and int_as_string_bitcount is None
        and not kw
    ):
        return _default_encoder.encode(obj)
    if cls is None:
        cls = JSONEncoder
    return cls(
        skipkeys=skipkeys, ensure_ascii=ensure_ascii,
        check_circular=check_circular, allow_nan=allow_nan, indent=indent,
        separators=separators, encoding=encoding, default=default,
        use_decimal=use_decimal,
        namedtuple_as_object=namedtuple_as_object,
        tuple_as_array=tuple_as_array,
        iterable_as_array=iterable_as_array,
        bigint_as_string=bigint_as_string,
        sort_keys=sort_keys,
        item_sort_key=item_sort_key,
        for_json=for_json,
        ignore_nan=ignore_nan,
        int_as_string_bitcount=int_as_string_bitcount,
        **kw).encode(obj)
github simplegeo / pyutil / pyutil / jsonutil.py View on Github external
from simplejson.decoder import JSONDecoder, JSONDecodeError
JSONDecoder, JSONDecodeError # http://divmod.org/trac/ticket/1499
from simplejson.encoder import JSONEncoder
def _import_OrderedDict():
    from pyutil.odict import OrderedDict
    return OrderedDict
OrderedDict = _import_OrderedDict()

def _import_c_make_encoder():
    from simplejson._speedups import make_encoder# XXX
    try:
        return make_encoder
    except ImportError:
        return None

_default_encoder = JSONEncoder(
    skipkeys=False,
    ensure_ascii=True,
    check_circular=True,
    allow_nan=True,
    indent=None,
    separators=None,
    encoding='utf-8',
    default=None,
    use_decimal=True,
)

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, **kw):
    """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
    ``.write()``-supporting file-like object).
github davepeck / game-of-go / www / simplejson / __init__.py View on Github external
__version__ = '2.0.2'
__all__ = [
    'dump', 'dumps', 'load', 'loads',
    'JSONDecoder', 'JSONEncoder',
]

if __name__ == '__main__':
    import warnings
    warnings.warn('python -msimplejson is deprecated, use python -msiplejson.tool', DeprecationWarning)
    from simplejson.decoder import JSONDecoder
    from simplejson.encoder import JSONEncoder
else:
    from decoder import JSONDecoder
    from encoder import JSONEncoder

_default_encoder = JSONEncoder(
    skipkeys=False,
    ensure_ascii=True,
    check_circular=True,
    allow_nan=True,
    indent=None,
    separators=None,
    encoding='utf-8',
    default=None,
)

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, **kw):
    """
    Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
    ``.write()``-supporting file-like object).
github odoo / odoo / openerpweb / nonliterals.py View on Github external
""" Manages the storage and lifecycle of non-literal domains and contexts
(and potentially other structures) which have to be evaluated with client data,
but still need to be safely round-tripped to and from the browser (and thus
can't be sent there themselves).
"""
import binascii
import hashlib
import simplejson.encoder

__all__ = ['Domain', 'Context', 'NonLiteralEncoder, non_literal_decoder']

#: 48 bits should be sufficient to have almost no chance of collision
#: with a million hashes, according to hg@67081329d49a
SHORT_HASH_BYTES_SIZE = 6

class NonLiteralEncoder(simplejson.encoder.JSONEncoder):
    def default(self, object):
        if not isinstance(object, (BaseDomain, BaseContext)):
            return super(NonLiteralEncoder, self).default(object)
        if isinstance(object, Domain):
            return {
                '__ref': 'domain',
                '__id': object.key
            }
        elif isinstance(object, Context):
            return {
                '__ref': 'context',
                '__id': object.key
            }
        elif isinstance(object, CompoundDomain):
            return {
                '__ref': 'compound_domain',
github simplejson / simplejson / simplejson / __init__.py View on Github external
import collections
    try:
        return collections.OrderedDict
    except AttributeError:
        from . import ordered_dict
        return ordered_dict.OrderedDict
OrderedDict = _import_OrderedDict()

def _import_c_make_encoder():
    try:
        from ._speedups import make_encoder
        return make_encoder
    except ImportError:
        return None

_default_encoder = JSONEncoder(
    skipkeys=False,
    ensure_ascii=True,
    check_circular=True,
    allow_nan=True,
    indent=None,
    separators=None,
    encoding='utf-8',
    default=None,
    use_decimal=True,
    namedtuple_as_object=True,
    tuple_as_array=True,
    iterable_as_array=False,
    bigint_as_string=False,
    item_sort_key=None,
    for_json=False,
    ignore_nan=False,
github ecolemo / djangobp / djangobp / httputil.py View on Github external
value = value.strftime('%Y.%m.%d %H:%M:%S') if type(value) == datetime else value
                value = '' if value is None else value
                value = '%s' % (value)
                result.append(value)
            worksheet.append(result)

        f = tempfile.NamedTemporaryFile(delete=True)
        workbook.save(f)
        f.seek(0, os.SEEK_SET)
        self.write(f.read())
        f.close()

def admin_export_as_excel(modeladmin, request, queryset):
    return HttpResponseExcel(request.path.replace('/', '_'), queryset, modeladmin.list_display)

class BSONEncoder(simplejson.encoder.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat() + 'Z'
#            return obj.strftime('%Y-%m-%dT%H:%M:%S')
        elif isinstance(obj, ObjectId) :
            return str(obj)
        else:
            return simplejson.JSONEncoder.default(self, obj)

#simplejson.JSONEncoder = BSONEncoder

logger = logging.getLogger(__name__)

class ErrorLoggingMiddleWare(object):
    def process_exception(self, request, exception):
        if request.path.startswith('/api'):
github google / personfinder / app / admin.py View on Github external
def get(self):
        user = users.get_current_user()
        simplejson.encoder.FLOAT_REPR = str
        encoder = simplejson.encoder.JSONEncoder(ensure_ascii=False)
        view_config = self.__model_config_to_view_config(self.config)
        view_config_json = dict(
                (name, encoder.encode(value))
                for name, value in view_config.iteritems())
        all_view_config_json = encoder.encode(view_config)

        #sorts languages by exonym; to sort by code, remove the key argument
        sorted_exonyms = sorted(list(const.LANGUAGE_EXONYMS.items()),
                                key= lambda lang: lang[1])
        sorted_exonyms = map(lambda elem: {'code' : elem[0],
                                           'exonym' : elem[1]}, sorted_exonyms)
        sorted_exonyms_json = encoder.encode(sorted_exonyms)
        repo_options = [Struct(repo=repo, url=self.get_url('/admin', repo))
                        for repo in sorted(Repo.list())]
        xsrf_tool = XsrfTool()
        self.render('admin.html',