Always return json content in the body of Exceptions to xhr requests.
172169
def json_exception(context, request):
    """"""
    request.response.status = context.code
    return {'error': context._status, 'messages': context.message}
180721
def get_json(environ):
    '''
    
    '''
    content_type = environ.get('CONTENT_TYPE', '')
    if content_type != 'application/json':
        raise HTTPError(406, 'JSON required')

    try:
        return salt.utils.json.loads(read_body(environ))
    except ValueError as exc:
        raise HTTPError(400, exc)
440196
function () {
                // Read response state from the memoized partial data.
                var _a = partialFromXhr(), headers = _a.headers, status = _a.status, statusText = _a.statusText, url = _a.url;
                // The body will be read out if present.
                var body = null;
                if (status !== 204) {
                    // Use XMLHttpRequest.response if set, responseText otherwise.
                    body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response;
                }
                // Normalize another potential bug (this one comes from CORS).
                if (status === 0) {
                    status = !!body ? 200 : 0;
                }
                // ok determines whether the response will be transmitted on the event or
                // error channel. Unsuccessful status codes (not 2xx) will always be errors,
                // but a successful status code can still result in an error if the user
                // asked for JSON data and the body cannot be parsed as such.
                var ok = status >= 200 && status < 300;
                // Check whether the body needs to be parsed as JSON (in many cases the browser
                // will have done that already).
                if (req.responseType === 'json' && typeof body === 'string') {
                    // Save the original body, before attempting XSSI prefix stripping.
                    var originalBody = body;
                    body = body.replace(XSSI_PREFIX, '');
                    try {
                        // Attempt the parse. If it fails, a parse error should be delivered to the user.
                        body = body !== '' ? JSON.parse(body) : null;
                    }
                    catch (error) {
                        // Since the JSON.parse failed, it's reasonable to assume this might not have been a
                        // JSON response. Restore the original body (including any XSSI prefix) to deliver
                        // a better error response.
                        body = originalBody;
                        // If this was an error request to begin with, leave it as a string, it probably
                        // just isn't JSON. Otherwise, deliver the parsing error to the user.
                        if (ok) {
                            // Even though the response status was 2xx, this is still an error.
                            ok = false;
                            // The parse error contains the text of the body that failed to parse.
                            body = { error: error, text: body };
                        }
                    }
                }
                if (ok) {
                    // A successful response is delivered on the event stream.
                    observer.next(new HttpResponse({
                        body: body,
                        headers: headers,
                        status: status,
                        statusText: statusText,
                        url: url || undefined,
                    }));
                    // The full body has been received and delivered, no further events
                    // are possible. This request is complete.
                    observer.complete();
                }
                else {
                    // An unsuccessful request is delivered on the error channel.
                    observer.error(new HttpErrorResponse({
                        // The error in this case is the response body (error from the server).
                        error: body,
                        headers: headers,
                        status: status,
                        statusText: statusText,
                        url: url || undefined,
                    }));
                }
            }
104603
function getJSON (response) {
  return response.json().then((body) => {
    if (body.status !== 'ok') {
      throw error(response, body.status, body.data[0])
    }
    return body
  })
}
490914
def get(self, endpoint):
        ''''''
        json_body = urlopen(self.url(endpoint)).read().decode('utf-8')
        return json.loads(json_body)
1339706
def get_content(request, page_id, content_id):
    """"""
    content = Content.objects.get(pk=content_id)
    return HttpResponse(content.body)
607285
def json(func):
    ""

    def wrapper(self, request, *args, **kwargs):
        try:
            response = {
                "success": True,
                "data": func(self, request, *args, **kwargs)
            }
        except GargoyleException, exc:
            response = {
                "success": False,
                "data": exc.message
            }
        except Switch.DoesNotExist:
            response = {
                "success": False,
                "data": "Switch cannot be found"
            }
        except ValidationError, e:
            response = {
                "success": False,
                "data": u','.join(map(unicode, e.messages)),
            }
        except Exception:
            if settings.DEBUG:
                import traceback
                traceback.print_exc()
            raise
        return HttpResponse(dumps(response), content_type="application/json")
    wrapper = wraps(func)(wrapper)
    return wrapper
839399
async def request(self, method, path, json=None):
        """"""
        url = 'https://{}:{}/api/'.format(self.host, self.port)
        url += path.format(site=self.site)

        try:
            async with self.session.request(method, url, json=json) as res:
                if res.content_type != 'application/json':
                    raise ResponseError(
                        'Invalid content type: {}'.format(res.content_type))
                response = await res.json()
                _raise_on_error(response)
                return response['data']

        except client_exceptions.ClientError as err:
            raise RequestError(
                'Error requesting data from {}: {}'.format(self.host, err)
            ) from None
838996
protected void returnJsonSystemError(HttpServletRequest request, HttpServletResponse response,
            ResultCode resultCode) throws IOException {
        Map<String, Object> errors = new HashMap<String, Object>();
        errors.put(WebResponseConstant.MESSAGE_GLOBAL, resultCode.getMessage().getMessage());
        JsonObject<?> json = JsonObject.create();
        json.setStatus(resultCode.getCode());
        json.setStatusInfo(errors);
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JsonUtils.toJson(json));
    }
91152
async def get_json(self, url, timeout=30, astext=False, exceptions=False):
        """"""
        try:
            with async_timeout.timeout(timeout):
                res = await self._aio_session.get(url)
                if res.status != 200:
                    _LOGGER.error("QSUSB returned %s [%s]", res.status, url)
                    return None
                res_text = await res.text()
        except (aiohttp.client_exceptions.ClientError,
                asyncio.TimeoutError) as exc:
            if exceptions:
                raise exc
            return None

        if astext:
            return res_text

        try:
            return json.loads(res_text)
        except json.decoder.JSONDecodeError:
            if res_text.strip(" ") == "":
                return None
            _LOGGER.error("Could not decode %s [%s]", res_text, url)
410536
def raw(self):
        
        try:
            return urlopen(str(self.url))
        except HTTPError as error:
            try:
                # parse error body as json and use message property as error message
                parsed = self._parsejson(error)
                exc = RequestError(parsed['message'])
                exc.__cause__ = None
                raise exc
            except ValueError:
                # when error body is not valid json, error might be caused by server
                exc = StatbankError()
                exc.__cause__ = None
                raise exc
1263866
def json(self):
        """"""
        lines = []
        for line in self.lines():
            try:
                if len(line) == 1:
                    lines.append(json.loads(line, strict=False))
                else:
                    lines.append(json.loads(line[1], strict=False))
            except ValueError:
                pass
        return lines
593662
def get_json_results(self, response):
        '''
        
        '''
        try:
            # return the proper JSON object, or error code if request didn't go through.
            self.most_recent_json = response.json()
            json_results = response.json()
            if response.status_code in [401, 403]: #401 is invalid key, 403 is out of monthly quota.
                raise PyMsCognitiveWebSearchException("CODE {code}: {message}".format(code=response.status_code,message=json_results["message"]) )
            elif response.status_code in [429]: #429 means try again in x seconds.
                message = json_results['message']
                try:
                    # extract time out seconds from response
                    timeout = int(re.search('in (.+?) seconds', message).group(1)) + 1
                    print ("CODE 429, sleeping for {timeout} seconds").format(timeout=str(timeout))
                    time.sleep(timeout)
                except (AttributeError, ValueError) as e:
                    if not self.silent_fail:
                        raise PyMsCognitiveWebSearchException("CODE 429. Failed to auto-sleep: {message}".format(code=response.status_code,message=json_results["message"]) )
                    else:
                        print ("CODE 429. Failed to auto-sleep: {message}. Trying again in 5 seconds.".format(code=response.status_code,message=json_results["message"]))
                        time.sleep(5)
        except ValueError as vE:
            if not self.silent_fail:
                raise PyMsCognitiveWebSearchException("Request returned with code %s, error msg: %s" % (r.status_code, r.text))
            else:
                print ("[ERROR] Request returned with code %s, error msg: %s. \nContinuing in 5 seconds." % (r.status_code, r.text))
                time.sleep(5)
        return json_results
630509
def request(method, path, params=None, data=None, auto_retry=True):
    
    body = None
    if data is not None:
        body = json.dumps(data, cls=utils.DateTimeEncoder)

    headers = {
        'accept': 'application/json',
        'content-type': 'application/json',
        'user-agent': analyzere.user_agent,
    }
    resp = request_raw(method, path, params=params, body=body, headers=headers,
                       auto_retry=auto_retry)
    content = resp.text
    if content:
        try:
            content = json.loads(content, cls=utils.DateTimeDecoder)
        except ValueError:
            raise errors.ServerError('Unable to parse JSON response returned '
                                     'from server.', resp, resp.status_code)
    return content
670329
def json_wrap(function, *args, **kwargs):
    ''''''
    try:
        # Some responses have data = None, but they generally signal a
        # successful API call as well.
        response = json.loads(function(*args, **kwargs).content)
        if 'data' in response:
            return response['data'] or True
        else:
            return response
    except Exception as exc:
        raise ClientException(exc)
1094066
def _json(self, response):
        
        if response.status_code == 204:
            return None
        try:
            return response.json()
        except ValueError as e:
            raise ValueError(
                'Exception: %s\n'
                'request: %s, response code: %s, response: %s' % (
                    str(e), response.request.url, response.status_code,
                    response.content,
                )
            )
77838
def json_loads(data):
    """"""
    if data is None:
        return ""

    if data == "-":
        return json.load(sys.stdin)
    elif os.path.exists(data):
        with open(data, 'r') as handle:
            return json.load(handle)
    else:
        return json.loads(data)