Serialize a queryset.
498395
def serialize(self, queryset, **options):
        
        self.options = options

        self.stream = options.get("stream", StringIO())
        self.primary_key = options.get("primary_key", None)
        self.properties = options.get("properties")
        self.geometry_field = options.get("geometry_field", "geom")
        self.use_natural_keys = options.get("use_natural_keys", False)
        self.bbox = options.get("bbox", None)
        self.bbox_auto = options.get("bbox_auto", None)
        self.srid = options.get("srid", GEOJSON_DEFAULT_SRID)
        self.crs = options.get("crs", True)

        self.start_serialization()

        if ValuesQuerySet is not None and isinstance(queryset, ValuesQuerySet):
            self.serialize_values_queryset(queryset)

        elif isinstance(queryset, list):
            self.serialize_object_list(queryset)

        elif isinstance(queryset, QuerySet):
            self.serialize_queryset(queryset)

        self.end_serialization()
        return self.getvalue()
668970
def serialize(self, value, primitive=False):
        """"""
        if hasattr(value, 'serialize'):
            # i.e. value is a nested model
            return value.serialize(primitive=primitive)
        else:
            return value
107923
def get_collections(self, data):
        """"""
        collections = self._filter_queryset('view_collection', data.collection_set.all())

        from .collection import CollectionSerializer

        class CollectionWithoutDataSerializer(WithoutDataSerializerMixin, CollectionSerializer):
            """Collection without data field serializer."""

        return self._serialize_items(CollectionWithoutDataSerializer, 'collections', collections)
659559
private void _serializeQuery(PageContext pc, Set test, Query query, StringBuilder sb, boolean serializeQueryByColumns, Set<Object> done) throws ConverterException {

	ApplicationContextSupport acs = (ApplicationContextSupport) pc.getApplicationContext();
	boolean preserveCase = acs.getSerializationSettings().getPreserveCaseForQueryColumn(); // UPPERCASE column keys by default for Query

	Collection.Key[] _keys = CollectionUtil.keys(query);
	sb.append(goIn());
	sb.append("{");

	/*
	 * 
	 * {"DATA":[["a","b"],["c","d"]]} {"DATA":{"aaa":["a","c"],"bbb":["b","d"]}}
	 */
	// Rowcount
	if (serializeQueryByColumns) {
	    sb.append("\"ROWCOUNT\":");
	    sb.append(Caster.toString(query.getRecordcount()));
	    sb.append(',');
	}

	// Columns
	sb.append("\"COLUMNS\":[");
	String[] cols = query.getColumns();
	for (int i = 0; i < cols.length; i++) {
	    if (i > 0) sb.append(",");
	    sb.append(StringUtil.escapeJS(preserveCase ? cols[i] : cols[i].toUpperCase(), '"', charsetEncoder));
	}
	sb.append("],");

	// Data
	sb.append("\"DATA\":");
	if (serializeQueryByColumns) {
	    sb.append('{');
	    boolean oDoIt = false;
	    int len = query.getRecordcount();
	    pc = ThreadLocalPageContext.get(pc);
	    boolean upperCase = false;
	    if (pc != null) upperCase = pc.getCurrentTemplateDialect() == CFMLEngine.DIALECT_CFML && ((ConfigWebImpl) pc.getConfig()).getDotNotationUpperCase();

	    for (int i = 0; i < _keys.length; i++) {
		if (oDoIt) sb.append(',');
		oDoIt = true;
		sb.append(goIn());

		sb.append(StringUtil.escapeJS(upperCase ? _keys[i].getUpperString() : _keys[i].getString(), '"', charsetEncoder));
		sb.append(":[");
		boolean doIt = false;
		for (int y = 1; y <= len; y++) {
		    if (doIt) sb.append(',');
		    doIt = true;
		    try {
			_serialize(pc, test, query.getAt(_keys[i], y), sb, serializeQueryByColumns, done);
		    }
		    catch (PageException e) {
			_serialize(pc, test, e.getMessage(), sb, serializeQueryByColumns, done);
		    }
		}

		sb.append(']');
	    }

	    sb.append('}');
	}
	else {
	    sb.append('[');
	    boolean oDoIt = false;
	    int len = query.getRecordcount();
	    for (int row = 1; row <= len; row++) {
		if (oDoIt) sb.append(',');
		oDoIt = true;

		sb.append("[");
		boolean doIt = false;
		for (int col = 0; col < _keys.length; col++) {
		    if (doIt) sb.append(',');
		    doIt = true;
		    try {
			_serialize(pc, test, query.getAt(_keys[col], row), sb, serializeQueryByColumns, done);
		    }
		    catch (PageException e) {
			_serialize(pc, test, e.getMessage(), sb, serializeQueryByColumns, done);
		    }
		}
		sb.append(']');
	    }
	    sb.append(']');
	}
	sb.append('}');
    }
105250
def serialize(d):
    
    ret = {}
    for k,v in d.items():
        if not k.startswith('_'):
            ret[k] = str(d[k])
    #ret['__class__'] = obj.__class__.__name__
    return ret
570775
def serialize(self, value, entity=None, request=None):
    

    ret = self.from_python(value)
    self.validate(ret)
    self.run_validators(value)
    return ret
966349
def _serialize_inputs(inputs):
        """"""
        serialized_inputs = {}
        for input_id, input_value in inputs.items():
            if isinstance(input_value, list):
                serialized_list = Task._serialize_input_list(input_value)
                serialized_inputs[input_id] = serialized_list
            else:
                if isinstance(input_value, File):
                    input_value = Task._to_api_file_format(input_value)
                serialized_inputs[input_id] = input_value
        return serialized_inputs
336043
def _serialize(self, value, attr, obj):
        
        # this might be an optional field
        if value:
            value = value.id

        return super(ForeignKeyField, self)._serialize(value, attr, obj)
195473
def serialize_params(self, params, complex=False):
        
        if complex:
            # See climata.acis for an example implementation
            raise NotImplementedError("Cannot serialize %s!" % params)
        else:
            # Simpler queries can use traditional URL parameters
            return {
                self.get_url_param(key): ','.join(val)
                for key, val in params.items()
            }
897032
def queryset(self, request, queryset):
        
        if self.value():
            parent = Question.objects.get(slug=self.value())
            return Choice.objects.child_of(parent).order_by('-id')
        return queryset
166677
def _serialize(self, value, attr, obj):
        """"""
        if isinstance(value, arrow.arrow.Arrow):
            value = value.datetime

        return super(ArrowField, self)._serialize(value, attr, obj)
380014
def serialize(self):
        
        expects = [exp.serialize() for exp in self.expects]
        converted_dict = {
            'id': self.id,
            'name': self.pretty_name,
            'raw_name': self.name,
            'doc': self.doc,
            'error': self.error,
            'skipped': self.skipped,
            'skip_reason': self.skip_reason,
            'execute_kwargs': self.safe_execute_kwargs,
            'metadata': self.metadata,
            'start': self.start_time,
            'end': self.end_time,
            'expects': expects,
            'success': self.success
        }
        return remove_empty_entries_from_dict(converted_dict)
333787
private String _serializeQuery(Query query, Set<Object> done) throws ConverterException {

	// fieldnames
	PageContext pc = ThreadLocalPageContext.get();
	boolean upperCase = false;
	if (pc != null) upperCase = pc.getCurrentTemplateDialect() == CFMLEngine.DIALECT_CFML && !((ConfigWebImpl) pc.getConfig()).preserveCase();

	StringBuilder fn = new StringBuilder();
	Collection.Key[] keys = CollectionUtil.keys(query);
	for (int i = 0; i < keys.length; i++) {
	    if (i > 0) fn.append(',');
	    fn.append(XMLUtil.escapeXMLString(upperCase ? keys[i].getUpperString() : keys[i].getString()));
	}

	StringBuilder sb = new StringBuilder(
		goIn() + "<recordset rowCount=" + del + query.getRecordcount() + del + " fieldNames=" + del + fn + del + " type=" + del + "coldfusion.sql.QueryTable" + del + ">");

	deep++;
	int len = query.getRecordcount();
	for (int i = 0; i < keys.length; i++) {
	    sb.append(goIn() + "<field name=" + del + XMLUtil.escapeXMLString(keys[i].getString()) + del + ">");
	    for (int y = 1; y <= len; y++) {
		try {
		    sb.append(_serialize(query.getAt(keys[i], y), done));
		}
		catch (PageException e) {
		    sb.append(_serialize(e.getMessage(), done));
		}
	    }

	    sb.append(goIn() + "</field>");
	}
	deep--;

	sb.append(goIn() + "</recordset>");
	return sb.toString();
    }
886856
def serialize(self, value, **kwargs):
        
        kwargs.update({'include_class': kwargs.get('include_class', True)})
        if self.serializer is not None:
            return self.serializer(value, **kwargs)
        if value is None:
            return None
        if isinstance(value, HasProperties):
            return value.serialize(**kwargs)
        return self.to_json(value, **kwargs)
1100242
def get_data(self, collection):
        """"""
        data = self._filter_queryset('view_data', collection.data.all())

        return self._serialize_data(data)
42251
def _serialize_items(self, serializer, kind, items):
        """"""
        if self.request and self.request.query_params.get('hydrate_{}'.format(kind), False):
            serializer = serializer(items, many=True, read_only=True)
            serializer.bind(kind, self)
            return serializer.data
        else:
            return [item.id for item in items]
658657
def serialize(self, obj, fields):
        

        data = {}
        remaining_fields = []
        for field in fields:
            if callable(field):  # Callable
                data[field.__name__] = field(obj)
            elif hasattr(self, field) and callable(getattr(self, field)):  # Method on the view
                data[field] = getattr(self, field)(obj)
            elif hasattr(obj, field):  # Callable/property/field on the model
                attr = getattr(obj, field)
                if isinstance(attr, Model):
                    data[field] = attr.pk
                elif isinstance(attr, Manager):
                    data[field] = [item['pk'] for item in attr.values('pk')]
                elif callable(attr):  # Callable on the model
                    data[field] = attr()
                else:
                    remaining_fields.append(field)
            else:
                raise AttributeError('Invalid field: %s' % field)

        # Add on db fields
        serializer = Serializer()
        serializer.serialize([obj], fields=list(remaining_fields))
        data.update(serializer.getvalue()[0]['fields'])

        # Any remaining fields should be properties on the model
        remaining_fields = set(remaining_fields) - set(data.keys())

        for field in remaining_fields:
            data[field] = getattr(obj, field)

        return data