Python json.encoder() Examples

The following are code examples for showing how to use json.encoder(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_pyjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__,
                         'json.scanner')
        self.assertEqual(self.json.decoder.scanstring.__module__,
                         'json.decoder')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         'json.encoder') 
Example 2
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_cjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__, '_json')
        self.assertEqual(self.json.decoder.scanstring.__module__, '_json')
        self.assertEqual(self.json.encoder.c_make_encoder.__module__, '_json')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         '_json') 
Example 3
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def additional_tests():
    suite = unittest.TestSuite()
    for mod in (json, json.encoder, json.decoder):
        suite.addTest(doctest.DocTestSuite(mod))
    suite.addTest(TestPyTest('test_pyjson'))
    suite.addTest(TestCTest('test_cjson'))
    return suite 
Example 4
Project: NiujiaoDebugger   Author: MrSrc   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def test_pyjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__,
                         'json.scanner')
        self.assertEqual(self.json.decoder.scanstring.__module__,
                         'json.decoder')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         'json.encoder') 
Example 5
Project: NiujiaoDebugger   Author: MrSrc   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def test_cjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__, '_json')
        self.assertEqual(self.json.decoder.scanstring.__module__, '_json')
        self.assertEqual(self.json.encoder.c_make_encoder.__module__, '_json')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         '_json') 
Example 6
Project: NiujiaoDebugger   Author: MrSrc   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def load_tests(loader, _, pattern):
    suite = unittest.TestSuite()
    for mod in (json, json.encoder, json.decoder):
        suite.addTest(doctest.DocTestSuite(mod))
    suite.addTest(TestPyTest('test_pyjson'))
    suite.addTest(TestCTest('test_cjson'))

    pkg_dir = os.path.dirname(__file__)
    return support.load_package_tests(pkg_dir, loader, suite, pattern) 
Example 7
Project: pyquarkchain   Author: QuarkChain   File: slogging.py    MIT License 5 votes vote down vote up
def format_message(self, msg, kwargs, highlight, level):
        if getattr(self, 'log_json', False):
            message = dict()
            message['event'] = '{}.{}'.format(
                self.name, msg.lower().replace(' ', '_'))
            message['level'] = logging.getLevelName(level)
            try:
                message.update(kwargs)
                try:
                    msg = json.dumps(message, cls=_LogJSONEncoder)
                except TypeError:
                    # Invalid value. With our custom encoder this can only happen with non-string
                    # dict keys (see: https://bugs.python.org/issue18820).
                    message = _stringify_dict_keys(message)
                    msg = json.dumps(message, cls=_LogJSONEncoder)
            except UnicodeDecodeError:
                message.update({
                    k: v if is_numeric(v) or isinstance(v, (float, complex)) else repr(v)
                    for k, v in kwargs.items()
                })
                msg = json.dumps(message, cls=_LogJSONEncoder)
        else:
            msg = "{}{} {}{}".format(
                bcolors.WARNING if highlight else "",
                msg,
                " ".join("{}={!s}".format(k, v) for k, v in kwargs.items()),
                bcolors.ENDC if highlight else ""
            )
        return msg 
Example 8
Project: ironpython2   Author: IronLanguages   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def test_pyjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__,
                         'json.scanner')
        self.assertEqual(self.json.decoder.scanstring.__module__,
                         'json.decoder')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         'json.encoder') 
Example 9
Project: ironpython2   Author: IronLanguages   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def test_cjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__, '_json')
        self.assertEqual(self.json.decoder.scanstring.__module__, '_json')
        self.assertEqual(self.json.encoder.c_make_encoder.__module__, '_json')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         '_json') 
Example 10
Project: ironpython2   Author: IronLanguages   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def additional_tests():
    suite = unittest.TestSuite()
    for mod in (json, json.encoder, json.decoder):
        suite.addTest(doctest.DocTestSuite(mod))
    suite.addTest(TestPyTest('test_pyjson'))
    suite.addTest(TestCTest('test_cjson'))
    return suite 
Example 11
Project: Computable   Author: ktraunmueller   File: __init__.py    MIT License 5 votes vote down vote up
def additional_tests():
    import json
    import json.encoder
    import json.decoder
    suite = unittest.TestSuite()
    for mod in (json, json.encoder, json.decoder):
        suite.addTest(doctest.DocTestSuite(mod))
    return suite 
Example 12
Project: oss-ftp   Author: aliyun   File: __init__.py    MIT License 5 votes vote down vote up
def test_pyjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__,
                         'json.scanner')
        self.assertEqual(self.json.decoder.scanstring.__module__,
                         'json.decoder')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         'json.encoder') 
Example 13
Project: oss-ftp   Author: aliyun   File: __init__.py    MIT License 5 votes vote down vote up
def test_cjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__, '_json')
        self.assertEqual(self.json.decoder.scanstring.__module__, '_json')
        self.assertEqual(self.json.encoder.c_make_encoder.__module__, '_json')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         '_json') 
Example 14
Project: oss-ftp   Author: aliyun   File: __init__.py    MIT License 5 votes vote down vote up
def additional_tests():
    suite = unittest.TestSuite()
    for mod in (json, json.encoder, json.decoder):
        suite.addTest(doctest.DocTestSuite(mod))
    suite.addTest(TestPyTest('test_pyjson'))
    suite.addTest(TestCTest('test_cjson'))
    return suite 
Example 15
Project: godot-zeronet-plugin   Author: zam-org   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def test_pyjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__,
                         'json.scanner')
        self.assertEqual(self.json.decoder.scanstring.__module__,
                         'json.decoder')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         'json.encoder') 
Example 16
Project: godot-zeronet-plugin   Author: zam-org   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def test_cjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__, '_json')
        self.assertEqual(self.json.decoder.scanstring.__module__, '_json')
        self.assertEqual(self.json.encoder.c_make_encoder.__module__, '_json')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         '_json') 
Example 17
Project: godot-zeronet-plugin   Author: zam-org   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def additional_tests():
    suite = unittest.TestSuite()
    for mod in (json, json.encoder, json.decoder):
        suite.addTest(doctest.DocTestSuite(mod))
    suite.addTest(TestPyTest('test_pyjson'))
    suite.addTest(TestCTest('test_cjson'))
    return suite 
Example 18
Project: blockhooks   Author: EthereumWebhooks   File: slogging.py    Apache License 2.0 5 votes vote down vote up
def format_message(self, msg, kwargs, highlight, level):
        if getattr(self, 'log_json', False):
            message = dict()
            message['event'] = '{}.{}'.format(self.name, msg.lower().replace(' ', '_'))
            message['level'] = logging.getLevelName(level)
            try:
                message.update(kwargs)
                try:
                    msg = json.dumps(message, cls=_LogJSONEncoder)
                except TypeError:
                    # Invalid value. With our custom encoder this can only happen with non-string
                    # dict keys (see: https://bugs.python.org/issue18820).
                    message = _stringify_dict_keys(message)
                    msg = json.dumps(message, cls=_LogJSONEncoder)
            except UnicodeDecodeError:
                message.update({
                    k: v if isnumeric(v) or isinstance(v, (float, complex)) else repr(v)
                    for k, v in kwargs.items()
                })
                msg = json.dumps(message, cls=_LogJSONEncoder)
        else:
            msg = "{}{} {}{}".format(
                bcolors.WARNING if highlight else "",
                msg,
                " ".join("{}={!s}".format(k, v) for k, v in kwargs.items()),
                bcolors.ENDC if highlight else ""
            )
        return msg 
Example 19
Project: Peerion   Author: hyperionxtech   File: slogging.py    Apache License 2.0 5 votes vote down vote up
def format_message(self, msg, kwargs, highlight, level):
        if getattr(self, 'log_json', False):
            message = dict()
            message['event'] = '{}.{}'.format(
                self.name, msg.lower().replace(' ', '_'))
            message['level'] = logging.getLevelName(level)
            try:
                message.update(kwargs)
                try:
                    msg = json.dumps(message, cls=_LogJSONEncoder)
                except TypeError:
                    # Invalid value. With our custom encoder this can only happen with non-string
                    # dict keys (see: https://bugs.python.org/issue18820).
                    message = _stringify_dict_keys(message)
                    msg = json.dumps(message, cls=_LogJSONEncoder)
            except UnicodeDecodeError:
                message.update({
                    k: v if is_numeric(v) or isinstance(v, (float, complex)) else repr(v)
                    for k, v in kwargs.items()
                })
                msg = json.dumps(message, cls=_LogJSONEncoder)
        else:
            msg = "{}{} {}{}".format(
                bcolors.WARNING if highlight else "",
                msg,
                " ".join("{}={!s}".format(k, v) for k, v in kwargs.items()),
                bcolors.ENDC if highlight else ""
            )
        return msg 
Example 20
Project: Wallet   Author: superbitcoin   File: __init__.py    MIT License 5 votes vote down vote up
def test_pyjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__,
                         'json.scanner')
        self.assertEqual(self.json.decoder.scanstring.__module__,
                         'json.decoder')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         'json.encoder') 
Example 21
Project: Wallet   Author: superbitcoin   File: __init__.py    MIT License 5 votes vote down vote up
def test_cjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__, '_json')
        self.assertEqual(self.json.decoder.scanstring.__module__, '_json')
        self.assertEqual(self.json.encoder.c_make_encoder.__module__, '_json')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         '_json') 
Example 22
Project: Wallet   Author: superbitcoin   File: __init__.py    MIT License 5 votes vote down vote up
def additional_tests():
    suite = unittest.TestSuite()
    for mod in (json, json.encoder, json.decoder):
        suite.addTest(doctest.DocTestSuite(mod))
    suite.addTest(TestPyTest('test_pyjson'))
    suite.addTest(TestCTest('test_cjson'))
    return suite 
Example 23
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def test_pyjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__,
                         'json.scanner')
        self.assertEqual(self.json.decoder.scanstring.__module__,
                         'json.decoder')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         'json.encoder') 
Example 24
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def test_cjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__, '_json')
        self.assertEqual(self.json.decoder.scanstring.__module__, '_json')
        self.assertEqual(self.json.encoder.c_make_encoder.__module__, '_json')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         '_json') 
Example 25
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def load_tests(loader, _, pattern):
    suite = unittest.TestSuite()
    for mod in (json, json.encoder, json.decoder):
        suite.addTest(doctest.DocTestSuite(mod))
    suite.addTest(TestPyTest('test_pyjson'))
    suite.addTest(TestCTest('test_cjson'))

    pkg_dir = os.path.dirname(__file__)
    return support.load_package_tests(pkg_dir, loader, suite, pattern) 
Example 26
Project: mo-parquet   Author: klahnakoski   File: encoder.py    Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, sort_keys=True):
        object.__init__(self)

        self.encoder = utf8_json_encoder 
Example 27
Project: mo-parquet   Author: klahnakoski   File: encoder.py    Mozilla Public License 2.0 5 votes vote down vote up
def encode(self, value, pretty=False):
        if pretty:
            return pretty_json(value)

        try:
            scrubbed = scrub(value)
            return text_type(self.encoder(scrubbed))
        except Exception as e:
            from mo_logs.exceptions import Except
            from mo_logs import Log

            e = Except.wrap(e)
            Log.warning("problem serializing {{type}}", type=text_type(repr(value)), cause=e)
            raise e 
Example 28
Project: cells   Author: AlesTsurko   File: __init__.py    MIT License 5 votes vote down vote up
def test_pyjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__,
                         'json.scanner')
        self.assertEqual(self.json.decoder.scanstring.__module__,
                         'json.decoder')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         'json.encoder') 
Example 29
Project: cells   Author: AlesTsurko   File: __init__.py    MIT License 5 votes vote down vote up
def test_cjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__, '_json')
        self.assertEqual(self.json.decoder.scanstring.__module__, '_json')
        self.assertEqual(self.json.encoder.c_make_encoder.__module__, '_json')
        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
                         '_json') 
Example 30
Project: cells   Author: AlesTsurko   File: __init__.py    MIT License 5 votes vote down vote up
def load_tests(loader, _, pattern):
    suite = unittest.TestSuite()
    for mod in (json, json.encoder, json.decoder):
        suite.addTest(doctest.DocTestSuite(mod))
    suite.addTest(TestPyTest('test_pyjson'))
    suite.addTest(TestCTest('test_cjson'))

    pkg_dir = os.path.dirname(__file__)
    return support.load_package_tests(pkg_dir, loader, suite, pattern) 
Example 31
Project: mos-horizon   Author: Mirantis   File: json_encoder.py    Apache License 2.0 4 votes vote down vote up
def iterencode(self, o, _one_shot=False):
        """The sole purpose of defining a custom JSONEncoder class is to
        override floatstr() inner function, or more specifically the
        representation of NaN and +/-float('inf') values in a JSON. Although
        Infinity values are not supported by JSON standard, we still can
        convince Javascript JSON.parse() to create a Javascript Infinity
        object if we feed a token `1e+999` to it.
        """
        if self.check_circular:
            markers = {}
        else:
            markers = None

        if self.ensure_ascii:
            _encoder = encoder.encode_basestring_ascii
        else:
            _encoder = encoder.encode_basestring

        # On Python 3, JSONEncoder has no more encoding attribute, it produces
        # an Unicode string
        if six.PY2 and self.encoding != 'utf-8':
            def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
                if isinstance(o, str):
                    o = o.decode(_encoding)
                return _orig_encoder(o)

        def floatstr(o, allow_nan=self.allow_nan, _repr=encoder.FLOAT_REPR,
                     _inf=encoder.INFINITY, _neginf=-encoder.INFINITY):
            # 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 = self.nan_str
            elif o == _inf:
                text = self.inf_str
            elif o == _neginf:
                text = '-' + self.inf_str
            else:
                return _repr(o)

            if not allow_nan:
                raise ValueError(
                    _("Out of range float values are not JSON compliant: %r") %
                    o)

            return text

        _iterencode = json.encoder._make_iterencode(
            markers, self.default, _encoder, self.indent, floatstr,
            self.key_separator, self.item_separator, self.sort_keys,
            self.skipkeys, _one_shot)
        return _iterencode(o, 0)