Hydrate basic:file and basic:json values.

    Find fields with basic:file type and assign a full path to the file.
    Find fields with basic:json type and assign a JSON object from storage.
160649
def _hydrate_values(output, output_schema, data):
    
    def hydrate_path(file_name):
        """Hydrate file paths."""
        from resolwe.flow.managers import manager

        class HydratedPath(str):
            """String wrapper, which also stores the original filename."""

            __slots__ = ('data_id', 'file_name')

            def __new__(cls, value=''):
                """Initialize hydrated path."""
                hydrated = str.__new__(cls, value)
                hydrated.data_id = data.id
                hydrated.file_name = file_name
                return hydrated

        return HydratedPath(manager.get_executor().resolve_data_path(data, file_name))

    def hydrate_storage(storage_id):
        """Hydrate storage fields."""
        from .storage import LazyStorageJSON  # Prevent circular import.

        return LazyStorageJSON(pk=storage_id)

    for field_schema, fields in iterate_fields(output, output_schema):
        name = field_schema['name']
        value = fields[name]
        if 'type' in field_schema:
            if field_schema['type'].startswith('basic:file:'):
                value['file'] = hydrate_path(value['file'])
                value['refs'] = [hydrate_path(ref) for ref in value.get('refs', [])]

            elif field_schema['type'].startswith('list:basic:file:'):
                for obj in value:
                    obj['file'] = hydrate_path(obj['file'])
                    obj['refs'] = [hydrate_path(ref) for ref in obj.get('refs', [])]

            if field_schema['type'].startswith('basic:dir:'):
                value['dir'] = hydrate_path(value['dir'])
                value['refs'] = [hydrate_path(ref) for ref in value.get('refs', [])]

            elif field_schema['type'].startswith('list:basic:dir:'):
                for obj in value:
                    obj['dir'] = hydrate_path(obj['dir'])
                    obj['refs'] = [hydrate_path(ref) for ref in obj.get('refs', [])]

            elif field_schema['type'].startswith('basic:json:'):
                fields[name] = hydrate_storage(value)

            elif field_schema['type'].startswith('list:basic:json:'):
                fields[name] = [hydrate_storage(storage_id) for storage_id in value]
1228122
function parseLocalData(fileObj, options, extendedData = {}) {
  fileObj.data = fileObj.data || {};
  for (const dataKey in fileObj.data) {
    const parsedField = parseField(dataKey, fileObj.data[dataKey], options);
    fileObj.data[dataKey] = parsedField.contents;
  }
  Object.assign(fileObj, extendedData);
  return fileObj;
}
644933
def from_json_path(path: str, check_version: bool = True) -> BELGraph:
    """"""
    with open(os.path.expanduser(path)) as f:
        return from_json_file(f, check_version=check_version)
766049
def search_json_log(filepath, key, value):
    
    try:
        with open(filepath, "r") as fh:
            for line in fh.readlines():
                    log = json.loads(line)
                    if key in log and log[key] == value:
                        return log
    except IOError:
        pass
    return False
508498
def _schema_to_json_file_object(self, schema_list, file_obj):
        
        json.dump(schema_list, file_obj, indent=2, sort_keys=True)
1134242
def read_file(file)
      json = JSON.parse(File.read(file))
      json.key?('definitions') ? json['definitions'] : {}
    end
988837
def _parse_json_with_fieldnames(self):
        
        for key in dir(self):
            if not key.startswith('_') and key not in self._TO_EXCLUDE:
                self.fieldnames.append(key)
                value = getattr(self, key)
                if value:
                    self.json[key] = value
        # Add OK attribute even if value is "False"
        self.json['ok'] = self.ok
1025549
function encodeFileToJson(file) {
    var filePath = file.getPath();
    if (!filePath) {
        return undefined;
    }

    return {
        path: filePath,
        mtime: file.getMTime(),
        type: file.getType()
    };
}
89478
def _get_main_and_json(directory):
    
    directory = os.path.normpath(os.path.abspath(directory))
    checker_main = os.path.normpath(os.path.join(directory, os.path.pardir, "checker-workflow-wrapping-tool.cwl"))
    if checker_main and os.path.exists(checker_main):
        main_cwl = [checker_main]
    else:
        main_cwl = glob.glob(os.path.join(directory, "main-*.cwl"))
        main_cwl = [x for x in main_cwl if not x.find("-pack") >= 0]
        assert len(main_cwl) == 1, "Did not find main CWL in %s" % directory
    main_json = glob.glob(os.path.join(directory, "main-*-samples.json"))
    assert len(main_json) == 1, "Did not find main json in %s" % directory
    project_name = os.path.basename(directory).split("-workflow")[0]
    return main_cwl[0], main_json[0], project_name
166751
def json_pretty_dump(obj, filename):
    
    with open(filename, "wt") as fh:
        json.dump(obj, fh, indent=4, sort_keys=4)
393901
def validate_json_file(file_list):
    
    for json_file in set(file_list):
        if not json_file.endswith(".json"):
            logger.log_warning("Only JSON file format can be validated, skip: {}".format(json_file))
            continue

        logger.color_print("Start to validate JSON file: {}".format(json_file), "GREEN")

        with io.open(json_file) as stream:
            try:
                json.load(stream)
            except ValueError as e:
                raise SystemExit(e)

        print("OK")
780713
function parse(base, key, value) {
  var type = typeof value;

  // resolve local JSON pointers
  if (key === 'href' && type === 'string') return formatHref(base, value);

  // TODO resolve "/" paths
  if (!value || type !== 'object') return value;

  var obj = copy(value);

  if (key === '' || obj.href) seal(base || obj.href, obj, []);

  return obj;
}
1319305
function(file, opts) {
	if (util.isObject(file) || util.isArray(file)) {
		return file;
	}

	var options = util.extend({
		asText: false, // true, false, 'pretty'
		javascript: false, // true, false
		scope: '', // directory to look for initial file
		variables: {
			// contains a key->value object with variables to @extends
		}
	}, opts);

	file = util.template(file, options.variables);

	/*****************************************************************************
	*  Initialize
	*****************************************************************************/

	var file_path;

	// If the file path is absolute use it
	// If not then prepend the current scope of the previous file.
	if (path.resolve(file) === path.normalize(file)) {
		file_path = path.normalize(file);
	}
	else {
		file_path = path.normalize(
			options.scope ? options.scope + '/' + file : file
		);
	}
	var class_json = parseFile(file_path, options);

	// Stores JSON objects of files that have to be merged together:
	// ["a", "b"]
	var file_list = util.isArray(class_json[indicators.EXTENDS]) ?
		class_json[indicators.EXTENDS] :
		class_json[indicators.EXTENDS] != null ?
			[ class_json[indicators.EXTENDS] ] :
			[];

	// Delete @extends from base_json to avoid infinitive recursion
	delete class_json[indicators.EXTENDS];

	// Push class_json to the path list:
	file_list.push(class_json);
	/*****************************************************************************
	*  Merge file by file
	*****************************************************************************/

	// default config for each file required:
	// set asText = false so we get an object returned
	// set scope = file's directory so there can be relative references
	var json_config = util.defaults({
		asText: false,
		scope: path.dirname(file_path),

		// _as is a hack so that we know its we are calling the function recursive
		_as: ANTI_SANITIZER
	}, options);

	// super_json is our output, start by containing first file in array
	var super_json = fromFile(file_list.shift(), json_config);

	// TODO: Figure out when to sanitize super_json hopefully we don't have to
	//   santize all returns. I'm not sure about this, and I'm not sure if we
	//   can even sanitize super_json when we return it.
	//   Is super_json used by anyone recursively?

	while (file_list.length) {
		var json = fromFile(file_list.shift(), json_config);

		merge(super_json, json);
	}

	// If this file is called from the outside eg json_merger.from...
	//   File('file_which_doesnt_extends_another_file.json')
	//   we need to sanitize the file and remove all indicators
	if (options._as != ANTI_SANITIZER) {
		super_json = util.sanitizeValue(super_json);
	}

	/*****************************************************************************
	*  Return super_json
	*****************************************************************************/
	if (options.asText) {
		return stringify(super_json, options);
	}
	else {
		return super_json;
	}
}
1080076
def find_json(raw):
    '''
    
    '''
    ret = {}
    lines = __split(raw)
    for ind, _ in enumerate(lines):
        try:
            working = '\n'.join(lines[ind:])
        except UnicodeDecodeError:
            working = '\n'.join(salt.utils.data.decode(lines[ind:]))

        try:
            ret = json.loads(working)  # future lint: blacklisted-function
        except ValueError:
            continue
        if ret:
            return ret
    if not ret:
        # Not json, raise an error
        raise ValueError
702418
def dump(self, file, sort_keys: bool = True, **kwargs) -> None:
        """"""
        json.dump(self.to_json(), file, sort_keys=sort_keys, **kwargs)
874515
def jsontype(self, name, path=Path.rootPath()):
        
        return self.execute_command('JSON.TYPE', name, str_path(path))
65582
def json(self):
        '''  '''
        if 'application/json' in self.environ.get('CONTENT_TYPE', '') \
        and 0 < self.content_length < self.MEMFILE_MAX:
            return json_loads(self.body.read(self.MEMFILE_MAX))
        return None