Wraps JSONified output for JSONP requests.
481051
def api(func):
    """"""
    @wraps(func)
    def decorated_function(*args, **kwargs):
        try:
            value = func(*args, **kwargs)
        except BaseException as e:
            value = {
                "status": "failed",
                "error": "Unkonwn error!"
            }
            flask.current_app.logger.error("Unkonwn error: %s" % str(e))
            flask.current_app.logger.exception(e)

        status = 200
        mimetype = 'application/json'
        content = json.dumps(value)
        callback = flask.request.args.get('callback', False)
        if callback:
            content = str(callback) + '(' + content + ')'
            mimetype = 'application/javascript'

        return flask.current_app.response_class(content, status=status, mimetype=mimetype)
    return decorated_function
165618
def wrap_output(output, encoding):
    """"""
    return codecs.getwriter(encoding)(output.buffer
                                      if hasattr(output, 'buffer')
                                      else output)
430075
def enhance_json_encode(api_instance, extra_settings=None):
    """"""
    api_instance.json_encoder = JSONEncodeManager()

    dumps_settings = {} if extra_settings is None else extra_settings
    dumps_settings['default'] = api_instance.json_encoder
    dumps_settings.setdefault('ensure_ascii', False)

    @api_instance.representation('application/json')
    def output_json(data, code, headers=None):
        if current_app.debug:
            dumps_settings.setdefault('indent', 4)
            dumps_settings.setdefault('sort_keys', True)

        dumped = json.dumps(data, **dumps_settings)
        if 'indent' in dumps_settings:
            dumped += '\n'

        resp = make_response(dumped, code)
        resp.headers.extend(headers or {})
        return resp
801494
def jsonify(self, status_code=None, message=None, headers=None):
        
        if status_code is None:
            status_code = self.status_code
        if message is None:
            message = self.message
        if headers is None:
            headers = self.headers
        response = flask.jsonify({
            'status_code': status_code,
            'error': repr(self),
            'message': message,
        })
        if status_code is not None:
            response.status_code = status_code
        if headers is not None:
            response.headers = headers
        return response
684713
def dump(*args, **kwargs):
    
    kwargs.update(dict(cls=NumpyEncoder,
                       sort_keys=True,
                       indent=4,
                       separators=(',', ': ')))
    return _json.dump(*args, **kwargs)
482305
def json_dumps(o):
    """"""
    return json.dumps(o, indent=4, sort_keys=True, ensure_ascii=True,
                      separators=(',', ': ')).encode('ascii')
767963
def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None):
        

        encoder = JSONEncoder(
            check_circular=self.app.validate_output,
            allow_nan=False,
            sort_keys=True,
            indent=2 if self.app.pretty_output else None,
            separators=(',', ': ') if self.app.pretty_output else (',', ':')
        )
        content = encoder.encode(response)
        if jsonp:
            content_list = [jsonp.encode(encoding), b'(', content.encode(encoding), b');']
        else:
            content_list = [content.encode(encoding)]
        return self.response(status, content_type, content_list, headers=headers)
202244
def render(self, data, accepted_media_type=None, renderer_context=None):
        

        wrapper = None
        success = False

        for wrapper_name in self.wrappers:
            wrapper_method = getattr(self, wrapper_name)
            try:
                wrapper = wrapper_method(data, renderer_context)
            except WrapperNotApplicable:
                pass
            else:
                success = True
                break

        if not success:
            raise WrapperNotApplicable(
                'No acceptable wrappers found for response.',
                data=data, renderer_context=renderer_context)

        renderer_context["indent"] = 4

        return super(JsonApiMixin, self).render(
            data=wrapper,
            accepted_media_type=accepted_media_type,
            renderer_context=renderer_context)
142598
def dict_jsonify(param):
    """"""
    if not isinstance(param, dict):
        param = dict(param)
    return jsonify(param)
543625
function jsonEncoder(input, path) {
    var output = new Stream();
    output.readable = true;
    var first = true;
    input.on("data", function (entry) {
      if (path) {
        entry.href = path + entry.name;
        var mime = entry.linkStat ? entry.linkStat.mime : entry.mime;
        if (mime && mime.match(/(directory|folder)$/)) {
          entry.href += "/";
        }
      }
      if (first) {
        output.emit("data", "[\n  " + JSON.stringify(entry));
        first = false;
      } else {
        output.emit("data", ",\n  " + JSON.stringify(entry));
      }
    });
    input.on("end", function () {
      if (first) output.emit("data", "[]");
      else output.emit("data", "\n]");
      output.emit("end");
    });
    if (input.pause) {
      output.pause = function () {
        input.pause();
      };
    }
    if (input.resume) {
      output.resume = function () {
        input.resume();
      };
    }
    return output;
  }
283756
function JSONMinifier() {
  const self = this;
  self.process = ({ output }) => JSON.stringify(JSON.parse(output));
}
1552
def jsonp(*args, **kw):
    
    data = json.dumps(dict(*args, **kw), indent=2)
    callback = request.args.get('callback', request.args.get('jsonp'))
    if callback and __jsoncallback_re.search(callback) is not None:
        data = callback + u'(' + data + u');'
        mimetype = 'application/javascript'
    else:
        mimetype = 'application/json'
    return Response(data, mimetype=mimetype)
472678
def write_json(self, **kwargs):
        
        self.stdout.write(json.dumps(kwargs) + "\n")
        self.stdout.flush()
557864
def json_response(func):
    

    @wraps(func)
    def wrapper(request, *args, **kwargs):
        res = func(request, *args, **kwargs)
        request.setHeader('Content-Type', 'application/json')
        return json.dumps(res)

    return wrapper
916468
def echo_json_response(response, pretty, limit=None, ndjson=False):
    ''''''
    indent = None
    sort_keys = False
    nl = False
    if not ndjson and (pretty or (pretty is None and sys.stdout.isatty())):
        indent = 2
        sort_keys = True
        nl = True
    try:
        if ndjson and hasattr(response, 'items_iter'):
            items = response.items_iter(limit)
            for item in items:
                click.echo(json.dumps(item))
        elif not ndjson and hasattr(response, 'json_encode'):
            response.json_encode(click.get_text_stream('stdout'), limit=limit,
                                 indent=indent, sort_keys=sort_keys)
        else:
            res = response.get_raw()
            res = json.dumps(json.loads(res), indent=indent,
                             sort_keys=sort_keys)
            click.echo(res)
        if nl:
            click.echo()
    except IOError as ioe:
        # hide scary looking broken pipe stack traces
        raise click.ClickException(str(ioe))
378197
def render_to_json(templates, context, request):
    
    html = render_to_string(
        templates,
        context=context,
        request=request
    )
    _json = json.dumps({
        "html": html
    })
    return HttpResponse(_json)
746933
def output(self, output, accepts, set_http_code, set_content_type):
		

		graph = Decorator._get_graph(output)
		if graph is not None:
			# decide the format
			output_mimetype, output_format = self.format_selector.decide(accepts, graph.context_aware)
			# requested content couldn't find anything
			if output_mimetype is None:
				set_http_code("406 Not Acceptable")
				return ['406 Not Acceptable'.encode('utf-8')]
			# explicitly mark text mimetypes as utf-8
			if 'text' in output_mimetype:
				output_mimetype = output_mimetype + '; charset=utf-8'

			# format the new response
			serialized = graph.serialize(format=output_format)
			set_content_type(output_mimetype)
			return [serialized]
		else:
			return output