Convert the value to a JSON compatible value
199129
def to_raw(self, value, context=None):
        """"""
        if value is None:
            return None
        res = {}
        value = value.copy()
        errors = []
        for field in list(set(value) & set(self._fields)):
            schema = self._fields.get(field)
            name = schema.get_attr('name', field)
            try:
                res[name] = \
                    schema.to_raw(value.pop(field), context=context)
            except exceptions.ValidationErrors as ex:
                self._update_errors_by_exception(errors, ex, name)

        self._raise_exception_when_errors(errors, value)
        res.update(value)
        return res
923880
def fromJSON(value):
        
        j = json.loads(value)
        v = GPDate()
        if "defaultValue" in j:
            v.value = j['defaultValue']
        else:
            v.value = j['value']
        if 'paramName' in j:
            v.paramName = j['paramName']
        elif 'name' in j:
            v.paramName = j['name']
        #from datetime import datetime
        #if isinstance(value, datetime):
            #v.value = local_time_to_online(value)
        #else:
            #v.value = value
        #v.paramName = j['paramName']
        return v
599870
def to_json(self):
        """"""

        j = {}
        for p in self.properties:
            try:
                v = getattr(self, p)
            except AttributeError:
                continue
            if v is not None:
                if p == 't':
                    j[p] = getattr(self, p).isoformat()
                else:
                    j[p] = getattr(self, p)

        return json.dumps(j)
582792
def fromJSON(value):
        """"""
        if isinstance(value, str):
            value = json.loads(value)
        elif isinstance(value, dict): pass
        else:
            raise AttributeError("Invalid input")
        return Extension(typeName=value['typeName'],
                         capabilities=value['capabilities'],
                         enabled=value['enabled'] == "true",
                         maxUploadFileSize=value['maxUploadFileSize'],
                         allowedUploadFileType=value['allowedUploadFileTypes'],
                         properties=value['properties'])
740678
def serialize_json_string(self, value):
        

        # Check if the value might be a json string
        if not isinstance(value, six.string_types):
            return value

        # Make sure it starts with a brace
        if not value.startswith('{') or value.startswith('['):
            return value

        # Try to load the string
        try:
            return json.loads(value)
        except:
            return value
486066
def to_json(value, **kwargs):
        
        def _recurse_list(val):
            if val and isinstance(val[0], list):
                return [_recurse_list(v) for v in val]
            return [str(v) if np.isnan(v) or np.isinf(v) else v for v in val]
        return _recurse_list(value.tolist())
584899
def fromJSON(value):
        
        j = json.loads(value)
        v = GPRasterDataLayer()
        if "defaultValue" in j:
            v.value = j['defaultValue']
        else:
            v.value = j['value']
        if 'paramName' in j:
            v.paramName = j['paramName']
        elif 'name' in j:
            v.paramName = j['name']
        return v
431923
def to_json(value, **kwargs):
        """"""
        if isinstance(value, HasProperties):
            return value.serialize(**kwargs)
        try:
            return json.loads(json.dumps(value))
        except TypeError:
            raise TypeError(
                "Cannot convert type {} to JSON without calling 'serialize' "
                "on an instance of Instance Property and registering a custom "
                "serializer".format(value.__class__.__name__)
            )
89182
private static JsonObject getJsonValueAsObject(JsonValue value) {
        return (value != null && value.getValueType() == ValueType.OBJECT) ? value.asJsonObject() : null;
    }
871996
def _get_json(value):
    """"""
    if hasattr(value, 'replace'):
        value = value.replace('\n', ' ')
    try:
        return json.loads(value)
    except json.JSONDecodeError:
        # Escape double quotes.
        if hasattr(value, 'replace'):
            value = value.replace('"', '\\"')
        # try putting the value into a string
        return json.loads('"{}"'.format(value))
1350921
function toJSON(value, options) {
  var propertyOrValues = {}
  var lines
  var isPropertyValuePair
  var pairs
  var values

  if (!options) {
    options = {}
  }

  if (options.log === null || options.log === undefined) {
    options.log = true
  }

  if (options.comment === null || options.comment === undefined) {
    options.comment = '%'
  }

  lines = value.split('\n')

  if (options.comment) {
    lines = lines.map(stripComments(options.comment))
  }

  lines = lines.map(trim).filter(Boolean)

  pairs = lines.map(toPropertyValuePairs(options.delimiter || ':'))

  pairs.forEach(function(line, index) {
    var currentLineIsPropertyValuePair

    currentLineIsPropertyValuePair = line.length === 2

    if (index === 0) {
      isPropertyValuePair = currentLineIsPropertyValuePair
    } else if (currentLineIsPropertyValuePair !== isPropertyValuePair) {
      throw new Error(
        'Error at `' +
          line +
          '`: ' +
          'Both property-value pairs and array values found. ' +
          'Make sure either exists.'
      )
    }

    if (own.call(propertyOrValues, line[0])) {
      if (
        !options.forgiving ||
        (options.forgiving === true &&
          currentLineIsPropertyValuePair &&
          line[1] !== propertyOrValues[line[0]])
      ) {
        throw new Error(
          'Error at `' +
            line +
            '`: ' +
            'Duplicate data found. ' +
            'Make sure, in objects, no duplicate properties exist;' +
            'in arrays, no duplicate values.'
        )
      }

      if (options.log) {
        if (
          options.forgiving === 'fix' &&
          propertyOrValues[line[0]] !== line[1]
        ) {
          console.log(
            'Overwriting `' +
              propertyOrValues[line[0]] +
              '` ' +
              'to `' +
              line[1] +
              '` for `' +
              line[0] +
              '`'
          )
        } else {
          console.log('Ignoring duplicate key for `' + line[0] + '`')
        }
      }
    }

    propertyOrValues[line[0]] = line[1]
  })

  if (isPropertyValuePair) {
    pairs.sort(sortOnFirstIndex)
    values = propertyValuePairsToObject(pairs)
  } else {
    lines.sort()
  }

  return values || lines
}
584322
function encodeJson(path, value) {
    var objInJson = {
            bn: cutils.getNumPath(path),
            e: []
        },
        pathType = cutils.getPathDateType(path),
        pathArray = cutils.getPathArray(path),
        oid = pathArray[0];

    if (pathType !== 'resource' && !_.isPlainObject(value))
        throw new TypeError('value should be an object.');

    switch (pathType) {
        case 'object':         // obj
            _.forEach(value, function (iObj, iid) {
                _.forEach(iObj, function (resrc, rid) {
                    if (_.isPlainObject(resrc)) {
                        _.forEach(resrc, function (r, riid) {
                            var data = encodeJsonValue(iid + '/' + cutils.ridNumber(oid, rid) + '/' + riid, r);
                            objInJson.e.push(data);
                        });
                    } else {
                        var data = encodeJsonValue(iid + '/' + cutils.ridNumber(oid, rid), resrc);
                        objInJson.e.push(data);
                    }
                });
            });
            break;

        case 'instance':         // inst
            _.forEach(value, function (resrc, rid) {
                if (_.isPlainObject(resrc)) {
                    _.forEach(resrc, function (r, riid) {
                        var data = encodeJsonValue(cutils.ridNumber(oid, rid) + '/' + riid, r);
                        objInJson.e.push(data);
                    });
                } else {
                    var data = encodeJsonValue(cutils.ridNumber(oid, rid), resrc);
                    objInJson.e.push(data);
                }
            });
            break;

        case 'resource':         // resrc
            if (_.isPlainObject(value)) {
                _.forEach(value, function (r, riid) {
                    var data = encodeJsonValue(riid, r);
                    objInJson.e.push(data);
                });
            } else {
                if (value instanceof Date) value = Number(value);
                var data = encodeJsonValue('', value);
                objInJson.e.push(data);
            }
            break;

        default:
            break;
     }

    return  cutils.bufferFrom(JSON.stringify(objInJson));
}
299229
def from_json(self, value):
        
        if value is None:
            return None

        if isinstance(value, six.binary_type):
            value = value.decode('utf-8')

        if isinstance(value, six.text_type):
            # Parser interprets empty string as now by default
            if value == "":
                return None
            try:
                value = dateutil.parser.parse(value)
            except (TypeError, ValueError):
                raise ValueError("Could not parse {} as a date".format(value))

        if not isinstance(value, datetime.datetime):
            raise TypeError(
                "Value should be loaded from a string, a datetime object or None, not {}".format(type(value))
            )

        if value.tzinfo is not None:  # pylint: disable=maybe-no-member
            return value.astimezone(pytz.utc)  # pylint: disable=maybe-no-member
        else:
            return value.replace(tzinfo=pytz.utc)
939194
def json(value):
    '''
    
    '''
    uncleaned = jsonlib.dumps(value)
    clean = bleach.clean(uncleaned)
    return mark_safe(clean)
745641
function format( value ) {
      // value was wrapped in array for parsing:
      try {
         return value.map( function( item ) {
            return JSON.stringify( item, null, 3 ).replace( NEWLINE_MATCHER, '\n' );
         } ).join( ',\n' );
      }
      catch( e ) {
         // value not JSON-compatible
         return value;
      }
   }
330454
def _bytes_to_json(value):
    """"""
    if isinstance(value, bytes):
        value = base64.standard_b64encode(value).decode("ascii")
    return value
1057642
private static String getJsonValue(JsonValue value) {
        String s = null;
        if (value != null) {
            s = getJsonValueAsString(value);
            if (s == null) {
                s = getJsonValueAsNumberString(value);
            }
            if (s == null) {
                Boolean b = getJsonValueAsBoolean(value);
                if (b != null) {
                    s = b ? "true" : "false";
                }
            }
        }
        return s;
    }