After modifying / preprocessing inputs,
    reformat the data in preparation for JSON serialization
345005
def _pack_data(X, Y, metadata):
    
    if not any(metadata):
        # legacy list of list format is acceptable
        return list(zip(X, Y))

    else:
        # newer dictionary-based format is required in order to save metadata
            return [
                {
                    'data': x,
                    'target': y,
                    'metadata': meta
                }
                for x, y, meta in zip(X, Y, metadata)
            ]
933035
def _preprocess(self, data):
        
        transformed_data = _copy(data)
        for name, step in self._transformers[:-1]:
            transformed_data = step.fit_transform(transformed_data)
            if type(transformed_data) != _tc.SFrame:
                raise RuntimeError("The transform function in step '%s' did not"
                    " return an SFrame (got %s instead)." % (name,
                                            type(transformed_data).__name__))
        return transformed_data
1018583
function formatsToJSON(attrs, options) {
        var defaultFormats = ['html'],
            formatsToKeep = options.formats || defaultFormats;

        // Iterate over all known formats, and if they are not in the keep list, remove them
        _.each(Post.allowedFormats, function (format) {
            if (formatsToKeep.indexOf(format) === -1) {
                delete attrs[format];
            }
        });

        return attrs;
    }
236959
def get_prep_value(self, value):
        """"""
        try:
            return json.dumps(value)
        except Exception as err:
            raise ValidationError(str(err))
269548
def _input_as_dict(self, data):
        
        # clear self._input; ready to receive new input and output files
        self._input = {}
        # Check that the arguments to the
        # subcommand-specific parameters are valid
        self.check_arguments()

        # Ensure that we have all required input (file I/O)
        for k in self._input_order:
            # N.B.: optional positional arguments begin with underscore (_)!
            # (e.g., see _mate_in for bwa bwasw)
            if k[0] != '_' and k not in data:
                raise MissingRequiredArgumentApplicationError("Missing "
                                                              "required "
                                                              "input %s" % k)

        # Set values for input and output files
        for k in data:
            # check for unexpected keys in the dict
            if k not in self._input_order:
                error_message = "Invalid input arguments (%s)\n" % k
                error_message += "Valid keys are: %s" % repr(self._input_order)
                raise InvalidArgumentApplicationError(error_message + '\n')

            # check for absolute paths
            if not isabs(data[k][0]):
                raise InvalidArgumentApplicationError("Only absolute paths "
                                                      "allowed.\n%s" %
                                                      repr(data))
            self._input[k] = data[k]

        # if there is a -f option to specify an output file, force the user to
        # use it (otherwise things to to stdout)
        if '-f' in self.Parameters and not self.Parameters['-f'].isOn():
            raise InvalidArgumentApplicationError("Please specify an output "
                                                  "file with -f")

        return ''
510430
def _input_to_dict(i, records, remapped=None):
    
    if not remapped: remapped = {}
    var_type, records = _to_variable_type(i["type"], records)
    if var_type.startswith("Array") and "inputBinding" in i.get("type", {}):
        ib = i["type"]["inputBinding"]
    elif "inputBinding" in i:
        ib = i["inputBinding"]
    else:
        ib = {"prefix": None, "itemSeparator": ";;", "position": None}
    name = _id_to_localname(i["id"]) if "id" in i else i["name"]
    return {"name": remapped.get(name) or name,
            "variable_type": var_type,
            "prefix": ib["prefix"], "separator": ib["itemSeparator"],
            "position": ib["position"], "is_required": True,
            "default": i.get("default", None), "separate": ib.get("separate", True)}, records
307323
def jsonify(result, format=False):
    '''  '''

    result2 = result.copy()
    if format:
        return json.dumps(result2, sort_keys=True, indent=4)
    else:
        return json.dumps(result2, sort_keys=True)
819971
def json_dumps(self, data):
        
        return json.dumps(
            data, 
            separators=(',', ':'), 
            sort_keys=True, 
            cls=self.json_encoder, 
            ensure_ascii=False
        ).encode('utf8')
240075
def pretty_dumps(data):
    
    try:
        return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False)
    except:
        return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=True)
333474
function formatOutput(obj) {
	if (argv.m) {
		return JSON.stringify(obj);
	}
	return JSON.stringify(obj, null, 2);
}
754185
def get_prep_value(self, value):
        '''
        '''
        if isinstance(value, JSON.JsonDict):
            return json.dumps(value, cls=JSON.Encoder)
        if isinstance(value, JSON.JsonList):
            return value.json_string
        if isinstance(value, JSON.JsonString):
            return json.dumps(value)
        return value
533843
def serialize_example(transformed_json_data, info_dict):
  
  import six
  import tensorflow as tf

  def _make_int64_list(x):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=x))
  def _make_bytes_list(x):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=x))
  def _make_float_list(x):
    return tf.train.Feature(float_list=tf.train.FloatList(value=x))

  if sorted(six.iterkeys(transformed_json_data)) != sorted(six.iterkeys(info_dict)):
    raise ValueError('Keys do not match %s, %s' % (list(six.iterkeys(transformed_json_data)),
                     list(six.iterkeys(info_dict))))

  ex_dict = {}
  for name, info in six.iteritems(info_dict):
    if info['dtype'] == tf.int64:
      ex_dict[name] = _make_int64_list(transformed_json_data[name])
    elif info['dtype'] == tf.float32:
      ex_dict[name] = _make_float_list(transformed_json_data[name])
    elif info['dtype'] == tf.string:
      ex_dict[name] = _make_bytes_list(transformed_json_data[name])      
    else:
      raise ValueError('Unsupported data type %s' % info['dtype'])

  ex = tf.train.Example(features=tf.train.Features(feature=ex_dict))
  return ex.SerializeToString()
885143
def _clean_data(api_response):
    '''
    
    '''
    data = {}
    data.update(api_response['DATA'])

    if not data:
        response_data = api_response['DATA']
        data.update(response_data)

    return data
658604
def prepare(data):
    """"""
    result = {}
    result["mode"] = data.get("mode")
    result["path"] = data.get("path")
    result["type"] = data.get("type")
    result["sha"] = data.get("sha")
    return result
947057
def prepare(data):
    """"""
    sha = data.get("sha")
    content = data.get("content")
    encoding = data.get("encoding")
    return {"sha": sha, "content": content, "encoding": encoding}
557518
def clean_post_data(self):
        """"""
        data = self.request.get('data')
        if not (data and self.request['method'] == 'post'):
            return self
        # case of total_data
        new_request = deepcopy(self.request)
        new_request.pop('data')
        self._add_task('total_data', data, new_request)

        # case of form_data
        if isinstance(data, dict):
            for key in data:
                new_request = deepcopy(self.request)
                new_form = deepcopy(data)
                new_form.pop(key)
                new_request['data'] = new_form
                self._add_task('form_data', key, new_request)
            return self

        # case of json_data
        try:
            json_data = json.loads(data.decode(self.encoding))
            for key in json_data:
                new_request = deepcopy(self.request)
                new_json = deepcopy(json_data)
                new_json.pop(key)
                new_request['data'] = json.dumps(new_json).encode(self.encoding)
                self._add_task('json_data', key, new_request)
            self.has_json_data = True
            return self
        except JSONDecodeError:
            return self
924189
def toJson(self, data=None, pretty=False):
        """"""
        if data==None: data = self.attrs
        data = self.flatten(data) # don't send objects as str in json
        #if pretty:
        ret = json.dumps(data, indent=4, sort_keys=True)
        #self.inflate() # restore objects from json str data
        return ret