Return a JSON response.

    This function is optimized for JSON following
    `Google JSON Style Guide <http://google-styleguide.googlecode.com/svn/trunk/jsoncstyleguide.xml>`_, but will handle
    any JSON except for HTTP errors.
332053
def respond_json(ctx, data, code = None, headers = [], json_dumps_default = None, jsonp = None):
    
    if isinstance(data, collections.Mapping):
        # Remove null properties as recommended by Google JSON Style Guide.
        data = type(data)(
            (name, value)
            for name, value in data.iteritems()
            if value is not None
            )
        error = data.get('error')
        if isinstance(error, collections.Mapping):
            error = data['error'] = type(error)(
                (name, value)
                for name, value in error.iteritems()
                if value is not None
                )
    else:
        error = None
    if jsonp:
        content_type = 'application/javascript; charset=utf-8'
    else:
        content_type = 'application/json; charset=utf-8'
    if error:
        code = code or error['code']
        assert isinstance(code, int)
        response = webob.exc.status_map[code](headers = headers)
        response.content_type = content_type
        if code == 204:  # No content
            return response
        if error.get('code') is None:
            error['code'] = code
        if error.get('message') is None:
            title = errors_title.get(code)
            title = ctx._(title) if title is not None else response.status
            error['message'] = title
    else:
        response = ctx.req.response
        response.content_type = content_type
        if code is not None:
            response.status = code
        response.headers.update(headers)
    # try:
    #     text = json.dumps(data, encoding = 'utf-8', ensure_ascii = False, indent = 2)
    # except UnicodeDecodeError:
    #     text = json.dumps(data, ensure_ascii = True, indent = 2)

    if json_dumps_default is None:
        text = json.dumps(data)
    else:
        text = json.dumps(data, default = json_dumps_default)
    text = unicode(text)
    if jsonp:
        text = u'{0}({1})'.format(jsonp, text)
    response.text = text
    return response
1143963
def json(self):
        

        if six.PY3:
            return json.loads(self.body.decode(self.charset))
        else:
            return json.loads(self.body)
1236961
def json_response(self, status=200, data={}, headers={}):
        '''
          
        '''
        mimetype = 'application/json'

        header_dict = {}
        for k, v in headers.items():
            header_dict[k] = v

        return Response(
            json.dumps(data),
            status=status,
            mimetype=mimetype,
            headers=header_dict)
199004
def json(
    body,
    status=200,
    headers=None,
    content_type="application/json",
    dumps=json_dumps,
    **kwargs
):
    
    return HTTPResponse(
        dumps(body, **kwargs),
        headers=headers,
        status=status,
        content_type=content_type,
    )
921631
def _get_json(self, url):
        
        self.log.info(u"/GET " + url)
        r = requests.get(url)
        if hasattr(r, 'from_cache'):
            if r.from_cache:
                self.log.info("(from cache)")
        if r.status_code != 200:
            throw_request_err(r)

        return r.json()
268325
function responseJSON(success, message, result = null, code) {
    return {
        success,
        message,
        result,
        code,
        time: new Date()
    }
}
1175926
def _get(url:str, headers:dict) -> dict:
    
    response = requests.get(url, headers=headers)

    data = response.json()
    if response.status_code != 200:
        raise GoogleApiError({"status_code": response.status_code,
                                  "error": data.get("error", "")})
    return data
1115793
function (res, res_obj) {

    // return response if exist, otherwise response might be returned 
    // AFTER some callback is done handling (i.e., response will be returned within the handler)
    if (typeof res_obj === 'string') {
        LOG.sys('replying a string: ' + res_obj);
        res.writeHead(200, {'Content-Type': 'text/plain'});                     
        res.end(res_obj);            
    }
    else {
        LOG.sys('replying a JSON: ' + JSON.stringify(res_obj));
        res.writeHead(200, {'Content-Type': 'application/json'});                     
        res.end(JSON.stringify(res_obj));        
    }
}
1119052
def returns_json(func):
    
    def decorator(*args, **kwargs):
        instance = args[0]
        request = getattr(instance, 'request', None)
        request.response.setHeader("Content-Type", "application/json")
        result = func(*args, **kwargs)
        return json.dumps(result)
    return decorator
104603
function getJSON (response) {
  return response.json().then((body) => {
    if (body.status !== 'ok') {
      throw error(response, body.status, body.data[0])
    }
    return body
  })
}
775196
def _json_request(self, method, path, data):
        

        response = self._request(method, path, data=data)
        _raise_for_status(response)
        if len(response.data) > 0:
            return _json_from_response(response)
        return response.data
817133
def _request_process_json(self, response):
        
        data = []
        try:
            if self._api_branch == 'bulk':
                response_data = self._request_bulk(response)
            else:
                response_data = response.json()

            if self._request_entity is None:
                data = response_data
                status = 'Success'
            elif self._api_branch == 'bulk':
                data, status = self._request_process_json_bulk(response_data)
            elif response_data.get('data') is None:
                data, status = self._request_process_json_status(response_data)
            elif response_data.get('status') == 'Success':
                data, status = self._request_process_json_standard(response_data)

                # setup pagination
                if self._result_count is None:
                    self._result_count = response_data.get('data', {}).get('resultCount')
            else:
                self.tcex.log.error('Failed Request: {}'.format(response.text))
                status = 'Failure'
        except KeyError as e:
            # TODO: Remove try/except block
            status = 'Failure'
            msg = u'Error: Invalid key {}. [{}] '.format(e, self.request_entity)
            self.tcex.log.error(msg)
        except ValueError as e:
            # TODO: Remove try/except block
            status = 'Failure'
            msg = u'Error: ({})'.format(e)
            self.tcex.log.error(msg)

        return data, status
992644
def _get(self, *args, **kwargs):
        
        response = requests.get(*args, **kwargs)

        response.raise_for_status()

        return response.json()
447270
function json(url, callback) {
    return request(url, function(req) {
      if (req.responseText) callback(JSON.parse(req.responseText));
    }, "application/json");
  }
644894
def http_response(self, request):
        '''
        '''
        content_types = request.content_types
        if not content_types or self._content_type in content_types:
            response = request.response
            response.content_type = self._content_type
            response.encoding = self.charset
            response.content = self.to_bytes()
            return response
        else:
            raise HttpException(status=415, msg=request.content_types)
607241
def resp_json(resp):
    
    if isinstance(resp, flask.Response):
        if 400 <= resp.status_code < 600:
            msg = resp.status
            try:
                result = loads(resp.data.decode("utf-8"))
                if isinstance(result, str):
                    msg = "%s, %s" % (resp.status, result)
                else:
                    msg = "%s %s, %s" % (
                        resp.status_code, result["error"], result["message"])
            except Exception:
                pass
            raise requests.HTTPError(msg, response=resp)
        else:
            return loads(resp.data.decode("utf-8"))
    else:
        try:
            resp.raise_for_status()
        except requests.HTTPError as ex:
            # the response may contains {"error": "", "message": ""}
            # append error and message to exception if possible
            try:
                result = resp.json()
                ex.args += (result["error"], result["message"])
            except (ValueError, KeyError):
                pass
            raise
        return resp.json()
84233
def _get_json_obj(self, endpoint, query, is_post=False):
        
        response = self._get_response(endpoint, query, is_post=is_post)
        content = response.text
        try:
            return loads(content)
        except ValueError:
            raise Exception('Could not decode content to JSON:\n%s'
                            % self.__class__.__name__, content)