我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用json.encoder()。
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')
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')
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
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
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)
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)