Glances API RESTful implementation.

        Return the JSON representation of a given plugin
        HTTP/200 if OK
        HTTP/400 if plugin is not found
        HTTP/404 if others error
979087
def _api(self, plugin):
        
        response.content_type = 'application/json; charset=utf-8'

        if plugin not in self.plugins_list:
            abort(400, "Unknown plugin %s (available plugins: %s)" % (plugin, self.plugins_list))

        # Update the stat
        self.__update__()

        try:
            # Get the JSON value of the stat ID
            statval = self.stats.get_plugin(plugin).get_stats()
        except Exception as e:
            abort(404, "Cannot get plugin %s (%s)" % (plugin, str(e)))
        return statval
1179285
function getJSON(jsonUrl, done) {
    var parsedUrl = url.parse(jsonUrl);
    
    var options = {
        "host" : parsedUrl.hostname,
        "hostname": parsedUrl.hostname,
        "port" : parsedUrl.port || 80,
        "path" : parsedUrl.pathname,
        "method" : "GET",
        // "agent" : false,
    };
    
    debug && console.error("prepublish:getJSON('" + jsonUrl + "', done)");
    debug && console.error("options=" + util.inspect(options));
    var req = http.get(options, function (res) {
        debug && console.error("STATUS: " + res.statusCode);
        debug && console.error("HEADERS: " + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        var data = '';
        res.on('data', function (chunk) {
            debug && console.error('getJSON: chunk="' + chunk + '"');
            data += chunk;
        });
        res.on('end', function() {
            debug && console.error('getJSON: end of request.');
            done(JSON.parse(data));
        });
    });

    req.on('error', function(error) {
        console.error("ERROR: " + error.message);
    });
}
1140754
def get_resource(url, headers):
    
    headers["Accept"] = "application/json"
    response = Catalyst_DAO().getURL(url, headers)

    if response.status != 200:
        raise DataFailureException(url, response.status, response.data)

    try:
        return json.loads(response.data)
    except ValueError as ex:
        raise DataFailureException(url, response.status, response.data)
709148
def _api_limits(self, plugin):
        
        response.content_type = 'application/json; charset=utf-8'

        if plugin not in self.plugins_list:
            abort(400, "Unknown plugin %s (available plugins: %s)" % (plugin, self.plugins_list))

        # Update the stat
        # self.__update__()

        try:
            # Get the JSON value of the stat limits
            ret = self.stats.get_plugin(plugin).limits
        except Exception as e:
            abort(404, "Cannot get limits for plugin %s (%s)" % (plugin, str(e)))
        return ret
616272
def restful(self, path, params):
        

        url = self._get_norm_base_url() + path
        response = requests.get(url, headers=self._get_rest_headers(), params=params)

        if response.status_code != 200:
            raise Exception(response)
        json_result = response.json(object_pairs_hook=OrderedDict)
        if len(json_result) == 0:
            return None
        else:
            return json_result
649227
def _do_request(self, url, params=None, data=None, headers=None):
        

        if not headers:
            headers = {'content-type': 'application/json'}

        try:
            response = requests.get(
                url, params=params, data=data, headers=headers)
        except:
            return None

        if response.status_code == 200:
            return response
703667
def set_json(self, obj, status=HttpStatusCodes.HTTP_200):
        
        obj = json.dumps(obj, sort_keys=True, default=lambda x: str(x))
        self.set_status(status)
        self.set_header(HttpResponseHeaders.CONTENT_TYPE, 'application/json')
        self.set_content(obj)
1032081
function returnJSON(finalResp, res) {
    if (JSONformat === 'JSON') {
      res.set('Content-Type', `application/json; charset=${encoding}`);
      res.json(finalResp);
    } else {
      res.set('Content-Type', `text/plain; charset=${encoding}`);
      res.send(JSON.stringify(finalResp));
    }
  }
529076
def inspect_plugin(self, name):
        
        url = self._url('/plugins/{0}/json', name)
        return self._result(self._get(url), True)
409470
def get_frontend_data_dict_for_plugin(request, plugin, editable):
    
    json_data = {}
    instance, plugin = plugin.get_plugin_instance()

    if not instance:
        return json_data

    renderer = renderer_pool.renderer_for_plugin(plugin)
    if renderer:
        json_data = renderer.render(request=request, plugin=plugin, instance=instance, editable=editable)

    if hasattr(plugin, 'parse_child_plugins') and plugin.parse_child_plugins:
        children = []
        for child_plugin in instance.get_children().order_by(settings.DJANGOCMS_SPA_PLUGIN_ORDER_FIELD):
            # Parse all children
            children.append(
                get_frontend_data_dict_for_plugin(
                    request=request,
                    plugin=child_plugin,
                    editable=editable
                )
            )

        if children:
            json_data['plugins'] = children

    return json_data
294385
def jsonp(func):
    """"""
    @wraps(func)
    def decorated(*args, **kwargs):
        callback = request.args.get('callback', False)
        if callback:
            data = str(func(*args, **kwargs).data)
            content = str(callback) + '(' + data + ')'
            mimetype = 'application/javascript'
            return current_app.response_class(content, mimetype=mimetype)
        else:
            return func(*args, **kwargs)
    return decorated
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)
207521
def py2json(py_obj):
    
    method = getattr(py_obj, '__json__', None)

    if method:
        return method()
    elif type(py_obj) == datetime.datetime:
        return py_obj.isoformat()
    elif type(py_obj) == datetime.date:
        return py_obj.isoformat()
    elif type(py_obj) == datetime.time:
        return py_obj.isoformat()
    elif type(py_obj) == set:
        return list(py_obj)
    elif type(py_obj) == decimal.Decimal:
        return str(py_obj)
    else:
        # look through custom plugins
        for encoder in _encoders:
            success, value = encoder(py_obj)
            if success:
                return value

        opts = (py_obj, type(py_obj))
        raise TypeError('Unserializable object {} of type {}'.format(*opts))
1010381
function json (opts) {
  return {
    ...opts,
    headers: {
      ...opts.headers,
      'content-type': 'application/json'
    },
    body: JSON.stringify(opts.body)
  }
}
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
972063
def getJson(url):
    """"""
    site = urllib2.urlopen(url, timeout=300)
    return json.load(site)
1300718
def json(self, **kwargs):
        """"""
        encoding = detect_encoding(self.content[:4])
        value = self.content.decode(encoding)

        return simplejson.loads(value, **kwargs)