当前位置: 首页>>代码示例>>Python>>正文


Python simplejson.JSONDecodeError方法代码示例

本文整理汇总了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"') 
开发者ID:gkudos,项目名称:qgis-cartodb,代码行数:24,代码来源:test_unicode.py

示例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 
开发者ID:thombashi,项目名称:pytablereader,代码行数:24,代码来源:core.py

示例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 
开发者ID:nttcom,项目名称:eclcli,代码行数:27,代码来源:api.py

示例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) 
开发者ID:ramses-tech,项目名称:nefertari,代码行数:25,代码来源:view.py

示例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 
开发者ID:ozmartian,项目名称:vidcutter,代码行数:18,代码来源:updater.py

示例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() 
开发者ID:Yelp,项目名称:schematizer,代码行数:19,代码来源:schema_migrations.py

示例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']
            )
        ) 
开发者ID:Yelp,项目名称:schematizer,代码行数:19,代码来源:compatibility.py

示例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 
开发者ID:SMAPPNYU,项目名称:smappPy,代码行数:19,代码来源:json_util.py

示例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) 
开发者ID:abhinavk99,项目名称:jikanpy,代码行数:21,代码来源:aiojikan.py

示例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) 
开发者ID:abhinavk99,项目名称:jikanpy,代码行数:21,代码来源:jikan.py

示例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() 
开发者ID:abhinavk99,项目名称:jikanpy,代码行数:22,代码来源:conftest.py

示例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() 
开发者ID:abhinavk99,项目名称:jikanpy,代码行数:24,代码来源:conftest.py

示例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) 
开发者ID:OpenConceptLab,项目名称:ocl_web,代码行数:22,代码来源:__init__.py

示例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 
开发者ID:mirnylab,项目名称:cooler,代码行数:19,代码来源:fileops.py

示例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
        ) 
开发者ID:apache,项目名称:incubator-superset,代码行数:23,代码来源:core.py


注:本文中的simplejson.JSONDecodeError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。