本文整理匯總了Python中simplejson.JSONDecodeError方法的典型用法代碼示例。如果您正苦於以下問題:Python simplejson.JSONDecodeError方法的具體用法?Python simplejson.JSONDecodeError怎麽用?Python simplejson.JSONDecodeError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類simplejson
的用法示例。
在下文中一共展示了simplejson.JSONDecodeError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_invalid_escape_sequences
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def test_invalid_escape_sequences(self):
# incomplete escape sequence
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u12')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u123')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1234')
# invalid escape sequence
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u123x"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u12x4"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1x34"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ux234"')
if sys.maxunicode > 65535:
# invalid escape sequence for low surrogate
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u0"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u00"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u000"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u000x"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u00x0"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u0x00"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\ux000"')
示例2: load_dict
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def load_dict(self):
self._validate()
self._logger.logging_load()
self.encoding = get_file_encoding(self.source, self.encoding)
buffer = []
with open(self.source, "r", encoding=self.encoding) as fp:
for line_idx, line in enumerate(fp):
line = line.strip()
if not line:
continue
try:
buffer.append(json.loads(line, object_pairs_hook=OrderedDict))
except json.JSONDecodeError as e:
raise ValidationError(
"line {line_idx}: {msg}: {value}".format(
line_idx=line_idx + 1, msg=e, value=line
)
)
return buffer
示例3: create
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def create(
self,
url,
session=None,
method=None,
**params
):
"""Create a new resource
:param string url:
The API-specific portion of the URL path
:param Session session:
HTTP client session
:param string method:
HTTP method (default POST)
"""
if not method:
method = 'POST'
ret = self._request(method, url, session=session, **params)
# Should this move into _requests()?
try:
return ret.json()
except json.JSONDecodeError:
return ret
示例4: prepare_request_params
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def prepare_request_params(self, _query_params, _json_params):
""" Prepare query and update params. """
self._query_params = dictset(
_query_params or self.request.params.mixed())
self._json_params = dictset(_json_params)
ctype = self.request.content_type
if self.request.method in ['POST', 'PUT', 'PATCH']:
if ctype == 'application/json':
try:
self._json_params.update(self.request.json)
except simplejson.JSONDecodeError:
log.error(
"Expecting JSON. Received: '{}'. "
"Request: {} {}".format(
self.request.body, self.request.method,
self.request.url))
self._json_params = BaseView.convert_dotted(self._json_params)
self._query_params = BaseView.convert_dotted(self._query_params)
self._params = self._query_params.copy()
self._params.update(self._json_params)
示例5: done
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def done(self, reply: QNetworkReply) -> None:
if reply.error() != QNetworkReply.NoError:
self.logger.error(reply.errorString())
sys.stderr.write(reply.errorString())
return
if os.getenv('DEBUG', False):
self.log_request(reply)
try:
jsonobj = loads(str(reply.readAll(), 'utf-8'))
reply.deleteLater()
latest = jsonobj.get('tag_name')
current = qApp.applicationVersion()
self.mbox.show_result(latest, current)
except JSONDecodeError:
self.logger.exception('Updater JSON decoding error', exc_info=True)
raise
示例6: get_schema_migration
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def get_schema_migration(request):
new_schema_json = request.json_body.get('new_schema')
old_schema_json = request.json_body.get('old_schema')
target_schema_type = request.json_body.get('target_schema_type')
_get_migration = SCHEMA_MIGRATION_STRATEGY_MAP.get(target_schema_type)
if _get_migration is None:
raise exceptions_v1.unsupported_target_schema_exception()
try:
return _get_migration(
new_avro_schema=json.loads(new_schema_json),
old_avro_schema=json.loads(old_schema_json)
if old_schema_json else {}
)
except json.JSONDecodeError:
raise exceptions_v1.invalid_schema_exception()
示例7: is_avro_schema_compatible
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def is_avro_schema_compatible(request):
try:
req = requests_v1.AvroSchemaCompatibilityRequest(**request.json_body)
return _is_schema_compatible(
req.schema_json,
req.namespace,
req.source
)
except simplejson.JSONDecodeError as e:
log.exception("Failed to construct AvroSchemaCompatibilityRequest. {}"
.format(request.json_body))
raise exceptions_v1.invalid_schema_exception(
'Error "{error}" encountered decoding JSON: "{schema}"'.format(
error=str(e),
schema=request.json_body['schema']
)
)
示例8: next
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def next(self):
read_buffer = self.stream.read(1)
while True:
try:
json_obj = json.loads(read_buffer)
if not self.stream.read(1) in [',',']']:
raise Exception('JSON seems to be malformed: object is not followed by comma (,) or end of list (]).')
return json_obj
except JSONDecodeError:
next_char = self.stream.read(1)
read_buffer += next_char
while next_char != '}':
next_char = self.stream.read(1)
if next_char == '':
raise StopIteration
read_buffer += next_char
示例9: _wrap_response
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def _wrap_response(
self,
response: aiohttp.ClientResponse,
url: str,
**kwargs: Union[int, Optional[str]],
) -> Dict[str, Any]:
"""Parses the response as json, then runs check_response and
add_jikan_metadata
"""
json_response: Dict[str, Any] = {}
try:
json_response = await response.json()
if not isinstance(json_response, dict):
json_response = {"data": json_response}
except (json.decoder.JSONDecodeError, simplejson.JSONDecodeError):
json_response = {"error": await response.text()}
if response.status >= 400:
raise APIException(response.status, json_response, **kwargs)
return utils.add_jikan_metadata(response, json_response, url)
示例10: _wrap_response
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def _wrap_response(
response: requests.Response, url: str, **kwargs: Union[int, Optional[str]]
) -> Dict[str, Any]:
"""Parses the response as json, then runs check_response and
add_jikan_metadata
"""
json_response: Dict[str, Any] = {}
try:
json_response = response.json()
if not isinstance(json_response, dict):
json_response = {"data": json_response}
except (json.decoder.JSONDecodeError, simplejson.JSONDecodeError):
# json failed to be parsed
# this could happen, for example, when someone has been IP banned
# and it returns the typical nginx 403 forbidden page
json_response = {"error": response.text}
if response.status_code >= 400:
raise APIException(response.status_code, json_response, **kwargs)
return utils.add_jikan_metadata(response, json_response, url)
示例11: response_mock
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def response_mock(use_json_decoder=True):
class ResponseMock:
def __init__(self):
self.status_code = 403
# simulate a banned user
self.text = """<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.15.5 (Ubuntu)</center>
</body>
</html>
"""
def json(self):
if use_json_decoder:
raise json.decoder.JSONDecodeError("Failed", "", 0)
raise simplejson.JSONDecodeError("Failed", "", 0)
return ResponseMock()
示例12: aio_response_mock
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def aio_response_mock(use_json_decoder=True):
class ResponseMock:
def __init__(self):
self.status = 403
async def json(self):
if use_json_decoder:
raise json.decoder.JSONDecodeError("Failed", "", 0)
raise simplejson.JSONDecodeError("Failed", "", 0)
async def text(self):
"""Simulate a banned user"""
return """<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.15.5 (Ubuntu)</center>
</body>
</html>
"""
return ResponseMock()
示例13: debug_result
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def debug_result(self, results):
"""
Some serious debug output.
"""
self.logger.debug('API %s' % (results.request.path_url))
self.logger.debug('%s RESULT: %s' % (
results.request.method, results.status_code))
if results.status_code == requests.codes.server_error:
self.logger.error(results.content)
elif len(results.content) > 0:
try:
self.logger.debug('%s JSON: %s' % (results.request.method,
json.dumps(results.json(),
sort_keys=True, indent=4,
separators=(',', ': '))))
except json.JSONDecodeError:
self.logger.error('%s %s JSON: Error decoding it: %s' % (results.request.method, results.request.path_url, results.content[:40]))
else:
self.logger.debug('%s no content.' % results.request.method)
示例14: decode_attr_value
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def decode_attr_value(obj):
"""Decode a numpy object or HDF5 attribute into a JSONable object"""
if hasattr(obj, "item"):
o = obj.item()
elif hasattr(obj, "tolist"):
o = obj.tolist()
elif isinstance(obj, six.string_types):
try:
o = datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S.%f")
except ValueError:
try:
o = json.loads(obj)
except JSONDecodeError:
o = obj
else:
o = obj
return o
示例15: sqllab
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import JSONDecodeError [as 別名]
def sqllab(self) -> FlaskResponse:
"""SQL Editor"""
payload = {
"defaultDbId": config["SQLLAB_DEFAULT_DBID"],
"common": common_bootstrap_payload(),
**self._get_sqllab_tabs(g.user.get_id()),
}
form_data = request.form.get("form_data")
if form_data:
try:
payload["requested_query"] = json.loads(form_data)
except json.JSONDecodeError:
pass
bootstrap_data = json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
)
return self.render_template(
"superset/basic.html", entry="sqllab", bootstrap_data=bootstrap_data
)