Serve JSON spec file
964705
def _openapi_json(self):
        """"""
        # We don't use Flask.jsonify here as it would sort the keys
        # alphabetically while we want to preserve the order.
        from pprint import pprint
        pprint(self.to_dict())
        return current_app.response_class(json.dumps(self.to_dict(), indent=4),
                                          mimetype='application/json')
1213145
def to_json_file(file, data, pretty):
    
    json_string = to_json(data, pretty)
    file_utils.write_to_file(file, json_string)
1124026
function getJsonResource(url) {

    var protocol = url.match(/^(.*?):/)
    protocol = (protocol && protocol[1]) || 'file'

    const defaultLoader = defaultOptions.loaders[protocol]
    const loader = options.loaders[protocol]

    return Promise.resolve(cache[url])
    .then(cached => {
      if(cached) {
        return cached
      } else {
        return loader(url, defaultOptions.loaders)
          .then(json => cache[url] = {raw: json, parsed: Array.isArray(json) ? [] : {} })
      }
    })
  }
1192270
function JsonParserStream(opts)
{
	var streamoptions;

	streamoptions = mod_jsprim.mergeObjects(opts,
	    { 'objectMode': true }, { 'highWaterMark': 0 });
	mod_stream.Transform.call(this, streamoptions);
	mod_vstream.wrapTransform(this, { 'name': 'json parser' });
}
801338
def load_json_file(json_file):
    
    with io.open(json_file, encoding='utf-8') as data_file:
        try:
            json_content = json.load(data_file)
        except exceptions.JSONDecodeError:
            err_msg = u"JSONDecodeError: JSON file format error: {}".format(json_file)
            logger.log_error(err_msg)
            raise exceptions.FileFormatError(err_msg)

        _check_format(json_file, json_content)
        return json_content
915317
function loadJson(filepath) {
	const json = fs.readFileSync(require.resolve(filepath), 'utf8');
	return JSON.parse(stripJsonComments(json));
}
644251
def load_json(json_object):
   '''  '''
   content = None
   if isinstance(json_object, str) and os.path.exists(json_object):
      with open_(json_object) as f:
         try:
            content = json.load(f)
         except Exception as e:
            debug.log("Warning: Content of '%s' file is not json."%f.name)
   elif hasattr(json_object, 'read'):
      try:
         content = json.load(json_object)
      except Exception as e:
         debug.log("Warning: Content of '%s' file is not json."%json_object.name)
   else:
      debug.log("%s\nWarning: Object type invalid!"%json_object)
   return content
173664
def load_json(filename):
    """"""
    try:
        if PY2:
            args = 'rb'
        else:
            args = 'r'
        with open(filename, args) as fid:
            data = json.load(fid)
        return data, None
    except Exception as err:
        return None, str(err)
991681
def serve_file(load, fnd):
    '''
    
    '''
    ret = {'data': '',
           'dest': ''}
    required_load_keys = ('path', 'loc', 'saltenv')
    if not all(x in load for x in required_load_keys):
        log.debug(
            'Not all of the required keys present in payload. Missing: %s',
            ', '.join(required_load_keys.difference(load))
        )
        return ret
    if not fnd['path']:
        return ret
    ret['dest'] = fnd['rel']
    gzip = load.get('gzip', None)
    fpath = os.path.normpath(fnd['path'])
    with salt.utils.files.fopen(fpath, 'rb') as fp_:
        fp_.seek(load['loc'])
        data = fp_.read(__opts__['file_buffer_size'])
        if data and six.PY3 and not salt.utils.files.is_binary(fpath):
            data = data.decode(__salt_system_encoding__)
        if gzip and data:
            data = salt.utils.gzip_util.compress(data, gzip)
            ret['gzip'] = gzip
        ret['data'] = data
    return ret
711084
function(spec, callback) { // eslint-disable-line camelcase
      spec = spec || {};
      if (!spec.ddoc) { throw new Error('index.del() must specify a "ddoc" value'); }
      if (!spec.name) { throw new Error('index.del() must specify a "name" value'); }
      var type = spec.type || 'json';
      var path = encodeURIComponent(db) + '/_index/' +
                 encodeURIComponent(spec.ddoc) + '/' +
                 encodeURIComponent(type) + '/' +
                 encodeURIComponent(spec.name);
      return nano.request({ path: path, method: 'delete' }, callback);
    }
1201359
function view_json(req, src, options, end) {
    load(src
        , {
            authorization: req.headers['authorization'],
            X_Forwarded_For: req.X_Forwarded_For
        }

        , function(status, result) {
            if (status !== true) {
                return end(false, 'status > ' + status);
            };

            result.get(['json'], function(status, data) {
                if (status == true) {
                    if (options.yaml) {
                        data = yaml.safeDump(data, {indent: options.yaml});
                    } else {
                        data = JSON.stringify(data, null, "\t");
                    };

                } else {
                    data = 'status > ' + status;
                };

                end(status, data);
            });
        }
    );
}
648533
def load_json(self, path):
        """"""
        with open(self.profile_path(path, must_exist=True),
                  encoding='utf-8') as f:
            data = json.load(f)
        return data
798353
function createSourceFilesMiddleware (filesPromise, serveFile, basePath, urlRoot) {
  return function (request, response, next) {
    const requestedFilePath = composeUrl(request.url, basePath, urlRoot)
    // When a path contains HTML-encoded characters (e.g %2F used by Jenkins for branches with /)
    const requestedFilePathUnescaped = composeUrl(querystring.unescape(request.url), basePath, urlRoot)

    request.pause()

    log.debug(`Requesting ${request.url}`)
    log.debug(`Fetching ${requestedFilePath}`)

    return filesPromise.then(function (files) {
      // TODO(vojta): change served to be a map rather then an array
      const file = findByPath(files.served, requestedFilePath) || findByPath(files.served, requestedFilePathUnescaped)
      const rangeHeader = request.headers['range']

      if (file) {
        const acceptEncodingHeader = request.headers['accept-encoding']
        const matchedEncoding = Object.keys(file.encodings).find(
          (encoding) => new RegExp(`(^|.*, ?)${encoding}(,|$)`).test(acceptEncodingHeader)
        )
        const content = file.encodings[matchedEncoding] || file.content

        serveFile(file.contentPath || file.path, rangeHeader, response, function () {
          if (/\?\w+/.test(request.url)) {
            common.setHeavyCacheHeaders(response) // files with timestamps - cache one year, rely on timestamps
          } else {
            common.setNoCacheHeaders(response) // without timestamps - no cache (debug)
          }
          if (matchedEncoding) {
            response.setHeader('Content-Encoding', matchedEncoding)
          }
        }, content, file.doNotCache)
      } else {
        next()
      }

      request.resume()
    })
  }
}
999195
def serve(self, filename):
        ''''''
        if not self.exists(filename):
            abort(404)
        return self.backend.serve(filename)
303964
def _load_json_file(json_file):
        
        with io.open(json_file, encoding='utf-8') as data_file:
            try:
                json_content = json.load(data_file)
            except p_exception.JSONDecodeError:
                err_msg = u"JSONDecodeError: JSON file format error: {}".format(json_file)
                raise p_exception.FileFormatError(err_msg)

            FileUtils._check_format(json_file, json_content)
            return json_content
484616
def load_from_json(file_path):
    """"""
    if os.path.exists(file_path):
        raw_data = open(file_path, 'rb').read()
        return json.loads(base64.decodestring(raw_data).decode('utf-8'))
1307226
function handler(req, res) {

        var path = cog.getConfig('options.api_data');
        var urlRegex = cog.getConfig('options.api_url_regex');
        var url = req.url.replace(/^\//, '').replace(/\/$/, '');

        console.log(req.method + ' ' + req.url);

        // Find the JSON-data file and serve it, if URL points to the API.
        if (path && urlRegex && urlRegex.test(url)) {
            var file = path + '/' + url + '.json';
            if (grunt.file.exists(file)) {
                res.end(grunt.file.read(file));
                return;
            }
        }

        if (req.method == 'POST') {
            // TODO: This needs fixing, since it throws an error.
            res.end('{"message": "OK"}');
        }

    }