Convert the input JSON value into python structures, raises
        django.core.exceptions.ValidationError if the data can't be converted.
326366
def to_python(self, value):
        
        if self.blank and not value:
            return {}
        value = value or '{}'
        if isinstance(value, six.binary_type):
            value = six.text_type(value, 'utf-8')
        if isinstance(value, six.string_types):
            try:
                # with django 1.6 i have '"{}"' as default value here
                if value[0] == value[-1] == '"':
                    value = value[1:-1]

                return json.loads(value)
            except Exception as err:
                raise ValidationError(str(err))
        else:
            return value
654318
def clean_data(input_value):

    ''' 
    '''

# pass normal json/yaml datatypes
    if input_value.__class__.__name__ in ['bool', 'str', 'float', 'int', 'NoneType']:
        pass

# transform byte data to base64 encoded string
    elif isinstance(input_value, bytes):
        from base64 import b64encode
        input_value = b64encode(input_value).decode()

# convert tuples and sets into lists
    elif isinstance(input_value, tuple) or isinstance(input_value, set):
        new_list = []
        new_list.extend(input_value)
        input_value = transform_data(clean_data, new_list)

# recurse through dictionaries and lists
    elif isinstance(input_value, dict) or isinstance(input_value, list):
        input_value = transform_data(clean_data, input_value)

# convert to string all python objects and callables
    else:
        input_value = str(input_value)

    return input_value
717695
def validate(self, instance, value):
        """"""
        if isinstance(value, datetime.datetime):
            return value
        if not isinstance(value, string_types):
            self.error(
                instance=instance,
                value=value,
                extra='Cannot convert non-strings to datetime.',
            )
        try:
            return self.from_json(value)
        except ValueError:
            self.error(
                instance=instance,
                value=value,
                extra='Invalid format for converting to datetime.',
            )
1024412
def convert(self):
        

        if self.is_type():
            return self.force_convert()

        raise TypeConversionError(
            "failed to convert from {} to {}".format(type(self._data).__name__, self.typename)
        )
616710
def from_dict(cls, data, model):
        
        model_provided = model is not None
        result = {}
        for name, new_value in data.items():
            kwargs = {
                'name': name,
                'new_value': new_value,
            }
            if model_provided:
                kwargs['params'] = model.get_field_params(name)
            result[name] = cls(**kwargs)
        return result
1275131
def from_json(cls, data):
        
        assert 'header' in data, 'Required keyword "header" is missing!'
        assert 'values' in data, 'Required keyword "values" is missing!'
        return cls(Header.from_json(data['header']), data['values'])
418059
def validate(self, raw_data, **kwargs):
        
        try:
            converted_data = int(raw_data)
            return super(IntegerField, self).validate(converted_data)
        except ValueError:
            raise ValidationException(self.messages['invalid'], repr(raw_data))
382580
def to_python(self, value):
        
        if value in validators.EMPTY_VALUES:
            return None
        if isinstance(value, datetime.datetime):
            return value.time()
        if isinstance(value, datetime.time):
            return value
        if isinstance(value, list):
            # Input comes from a 2 SplitTimeWidgets, for example. So, it's two
            # components: start time and end time.
            if len(value) != 2:
                raise ValidationError(self.error_messages['invalid'])
            if value[0] in validators.EMPTY_VALUES and value[1] in \
                    validators.EMPTY_VALUES:
                return None

            start_value = value[0]
            end_value = value[1]

        start_time = None
        end_time = None

        for format in self.input_formats or formats.get_format(\
                'TIME_INPUT_FORMATS'):
            try:
                start_time = datetime.datetime(
                    *time.strptime(start_value, format)[:6]
                ).time()
            except ValueError:
                if start_time:
                    continue
                else:
                    raise ValidationError(self.error_messages['invalid'])

        for format in self.input_formats or formats.get_format(\
                'TIME_INPUT_FORMATS'):
            try:
                end_time = datetime.datetime(
                    *time.strptime(end_value, format)[:6]
                ).time()
            except ValueError:
                if end_time:
                    continue
                else:
                    raise ValidationError(self.error_messages['invalid'])

        return (start_time, end_time)
1287211
def to_json(value, **kwargs):
        
        b64rep = base64.b64encode(value.read())
        value.seek(0)
        jsonrep = '{preamble}{b64}'.format(
            preamble=PNG_PREAMBLE,
            b64=b64rep.decode(),
        )
        return jsonrep
139459
def to_python(self, value):
        """"""
        cache = None
        if value is None:
            return None

        if isinstance(value, DataDescriptor):
            return value
        elif isinstance(value, dict):
            # Allow pre-hydrated data objects.
            cache = value
            try:
                value = cache['__id']
            except KeyError:
                raise ValidationError("dictionary must contain an '__id' element")
        elif not isinstance(value, int):
            raise ValidationError("field must be a DataDescriptor, data object primary key or dict")

        return DataDescriptor(value, self, cache)
826615
def validate(self, value, model_instance):
        """"""
        if isinstance(value, six.string_types):
            super(JSONField, self).validate(value, model_instance)
            try:
                json.loads(value)
            except Exception as err:
                raise ValidationError(str(err))
97362
def _JsonValueToPythonValue(json_value):
    """"""
    util.Typecheck(json_value, JsonValue)
    _ValidateJsonValue(json_value)
    if json_value.is_null:
        return None
    entries = [(f, json_value.get_assigned_value(f.name))
               for f in json_value.all_fields()]
    assigned_entries = [(f, value)
                        for f, value in entries if value is not None]
    field, value = assigned_entries[0]
    if not isinstance(field, messages.MessageField):
        return value
    elif field.message_type is JsonObject:
        return _JsonObjectToPythonValue(value)
    elif field.message_type is JsonArray:
        return _JsonArrayToPythonValue(value)
732284
def json_encode(data):
    

    def _any(data):
        ret = None
        # Opps, we used to check if it is of type list, but that fails 
        # i.e. in the case of django.newforms.utils.ErrorList, which extends
        # the type "list". Oh man, that was a dumb mistake!
        if isinstance(data, list):
            ret = _list(data)
        # Same as for lists above.
        elif isinstance(data, dict):
            ret = _dict(data)
        elif isinstance(data, Decimal):
            # json.dumps() cant handle Decimal
            ret = str(data)
        elif isinstance(data, models.query.QuerySet):
            # Actually its the same as a list ...
            ret = _list(data)
        elif isinstance(data, models.Model):
            ret = _model(data)
        # here we need to encode the string as unicode (otherwise we get utf-16 in the json-response)
        elif isinstance(data, basestring):
            ret = unicode(data)
        # see http://code.djangoproject.com/ticket/5868
        elif isinstance(data, Promise):
            ret = force_unicode(data)
        else:
            ret = data
        return ret
    
    def _model(data):
        ret = {}
        # If we only have a model, we only want to encode the fields.
        for f in data._meta.fields:
            ret[f.attname] = _any(getattr(data, f.attname))
        # And additionally encode arbitrary properties that had been added.
        fields = dir(data.__class__) + ret.keys()
        add_ons = [k for k in dir(data) if k not in fields if k != '_state']
        for k in add_ons:
            ret[k] = _any(getattr(data, k))
        return ret
    
    def _list(data):
        ret = []
        for v in data:
            ret.append(_any(v))
        return ret
    
    def _dict(data):
        ret = {}
        for k,v in data.items():
            ret[k] = _any(v)
        return ret
    
    ret = _any(data)
    return json.dumps(ret, cls=DateTimeAwareJSONEncoder)
794593
def to_python(self, value):
        """"""
        if isinstance(value, FileDescriptor):
            return value
        elif isinstance(value, str):
            return FileDescriptor(value)
        elif isinstance(value, dict):
            try:
                path = value['file']
            except KeyError:
                raise ValidationError("dictionary must contain a 'file' element")

            if not isinstance(path, str):
                raise ValidationError("field's file element must be a string")

            size = value.get('size', None)
            if size is not None and not isinstance(size, int):
                raise ValidationError("field's size element must be an integer")

            total_size = value.get('total_size', None)
            if total_size is not None and not isinstance(total_size, int):
                raise ValidationError("field's total_size element must be an integer")

            is_remote = value.get('is_remote', None)
            if is_remote is not None and not isinstance(is_remote, bool):
                raise ValidationError("field's is_remote element must be a boolean")

            file_temp = value.get('file_temp', None)
            if file_temp is not None and not isinstance(file_temp, str):
                raise ValidationError("field's file_temp element must be a string")

            refs = value.get('refs', None)
            if refs is not None and not isinstance(refs, list):
                # TODO: Validate that all refs are strings.
                raise ValidationError("field's refs element must be a list of strings")

            return FileDescriptor(
                path,
                size=size,
                total_size=total_size,
                is_remote=is_remote,
                file_temp=file_temp,
                refs=refs,
            )
        elif not isinstance(value, None):
            raise ValidationError("field must be a FileDescriptor, string or a dict")
676925
def get_prep_value(self, value):
        """"""

        if value == "":
            return None

        if isinstance(value, dict):
            value = json.dumps(value, cls=DjangoJSONEncoder)

        return value
482594
def to_python(cls, value, **kwargs):
        """"""
        if not value:
            return ''
        try:
            return str(value)
        except:
            pass
        try:
            return value.encode('utf-8')
        except:
            pass
        raise cls.exception("Cannot deserialize value {0} tostring".format(value))
189927
def to_python(self, value):
        
        value = '' if value in validators.EMPTY_VALUES else smart_text(value)
        if value == self.empty_value or value in validators.EMPTY_VALUES:
            return self.empty_value
        try:
            value = self.coerce(value)
        except (ValueError, TypeError, ValidationError):
            self._on_invalid_value(value)
        return value