Exemplo n.º 1
0
def decodeBSONEntity(di, key):
    """
        Inspired by pymongo bson.json_util.default, but specially processing some value types:

        ObjectId --> hexvalue
        datetime --> rfc3339

        Also, while json_util.default creates a new dict in the form {$name: decodedvalue} we assign
        the decoded value, 'flattening' the value directly in the field.

        Fallback to other values using json_util.default, and flattening only those decoded entities
        that has only one key.
    """
    value = di[key]
    if isinstance(value, ObjectId):
        di[key] = str(value)
        return
    if isinstance(value, datetime):
        di[key] = rfc3339(value, utc=True, use_system_timezone=False)
        return
    try:
        decoded = json_util.default(di[key])
        if len(decoded.keys()) == 1:
            di[key] = decoded[decoded.keys()[0]]
        else:
            di[key] = decoded
    except:
        pass
Exemplo n.º 2
0
def default(obj):
    if isinstance(obj,matrix):
        obj = { "$matrix": obj.T.tolist() }
    else:
        obj = json_util.default(obj)
        
    return obj
Exemplo n.º 3
0
def default_date(obj):
    try:
        return json_util.default(obj)
    except TypeError:
        if isinstance(obj, date):
            return {"$date_only": obj.isoformat()}
    raise TypeError("%r is not JSON serializable" % obj)
Exemplo n.º 4
0
Arquivo: dto.py Projeto: sokky/gazoBBS
 def default(self, obj):
     #_idはObjectId型で、JSONではSerializeできない。よって変換する
     if isinstance(obj, ObjectId):
         return json_util.default(obj)
     elif isinstance(obj, datetime):
         return obj.strftime("%Y-%m-%d %H:%M:%S")
     else:
         return obj
     return json.JSONEncoder.default(self, obj)
Exemplo n.º 5
0
def json_formater(obj):
	if isinstance(obj, ObjectId):
		return str(obj)

	if isinstance(obj, datetime):
		return obj.isoformat()
		

	return json_util.default(obj)
Exemplo n.º 6
0
def json_convert(obj):

    if isinstance(obj, ObjectId):
        return str(obj)
    
    elif isinstance(obj, datetime):        
        return arrow.get(obj).for_json() #'2015-11-16T23:38:04.551214+00:00'

    return json_util.default(obj)
Exemplo n.º 7
0
def to_json(obj):
    if isinstance(obj, ObjectId):
        return str(obj)
    elif isinstance(obj, DBRef):
        return {"collection": obj.collection, "id": str(obj.id)}
    elif isinstance(obj, datetime.datetime):
        return obj.isoformat()
    else:
        return default(obj)
Exemplo n.º 8
0
def to_json(obj):
    if isinstance(obj, ObjectId):
        return str(obj)
    elif isinstance(obj, DBRef):
        return {'collection': obj.collection, 'id': str(obj.id)}
    elif isinstance(obj, datetime.datetime):
        return obj.isoformat()
    elif isinstance(obj, set):
        return list(obj)
    else:
        return default(obj)
Exemplo n.º 9
0
def to_jsonable(obj):
    if isinstance(obj, datetime.datetime):
        return obj.isoformat()
    if isinstance(obj, ObjectId):
        return json_util.default(obj)
    props = dir(obj)
    if 'to_dict' in props:
        return obj.as_dict()
    if '__iter__' in props:
        return list(obj)
    raise TypeError('Cannot serialize {} of type {}'.format(obj, type(obj)))
Exemplo n.º 10
0
def to_json(data):
	"""Convert a BSON value to something JSON serialiseable, 
	using json_util.default.
	"""
	if isinstance(data, dict):
		return dict((key, to_json(value)) for key, value in data.iteritems())
	elif isinstance(data, (list, Cursor)):
		return map(to_json, data)
	else:
		try:
			return default(data)
		except TypeError:
			return data
Exemplo n.º 11
0
 def default(self, obj):
     if hasattr(obj, 'iteritems') or hasattr(obj, 'items'):  # PY3 support
         return dict(((k, self.default(v)) for k, v in obj.iteritems()))
     elif hasattr(obj, '__iter__') and not isinstance(obj, string_types):
         return list((self.default(v) for v in obj))
     try:
         if isinstance(obj, ObjectId):
             return str(obj)
         elif isinstance(obj, datetime.datetime):
             return obj.isoformat()
         else:
             return json_util.default(obj)
     except TypeError:
         return obj
Exemplo n.º 12
0
    def serialize(self, obj):
        if isinstance(obj, ObjectId):
            return str(obj)

        if isinstance(obj, MongoModel):
            ret = {}
            for k in obj.__columns__.keys():
                ret_k = self.column_mapping.get(k, k)
                if getattr(obj.__class__, 'visible_columns', None):
                    if k in obj.visible_columns:
                        ret[ret_k] = getattr(obj, k)
                else:
                    ret[ret_k] = getattr(obj, k)

            if getattr(obj, 'serialize', None):
                for k in obj.serialize:
                    ret[k] = getattr(obj, k)
            return ret
        return json_util.default(obj)
Exemplo n.º 13
0
def _default(obj):
	"""
	Custom conversion of BSON types
	"""
	if isinstance(obj, datetime.datetime):
		return obj.strftime("%Y-%m-%d %H:%M:%S")
	elif isinstance(obj, ObjectId):
		return str(obj)
	elif isinstance(obj, float):
		if (math.isnan(obj)):
			return '$float___nan'
		elif (math.isinf(obj)):
			if (obj > 0):
				return '$float___inf'
			else:
				return '$float___-inf'
		else:
			return obj
	else:
		return default(obj)
Exemplo n.º 14
0
        def default(self, obj):
            # use the Flask default if possible
            try:
                return super(BSONJSONEncoder, self).default(obj)
            except TypeError as exception:
                pass

            # use a simple string for ObjectId
            if isinstance(obj, ObjectId):
                return str(obj)

            # try the BSON encoder for other BSON types
            try:
                return bson_json_util.default(obj)
            except TypeError:
                pass

            # general iterables aren't handled by any of the other encoders
            if isinstance(obj, collections.Iterable):
                return list(obj)

            # finally, re-raise the original TypeError exception
            raise exception
Exemplo n.º 15
0
 def default(self, obj):
     return json_util.default(obj)
Exemplo n.º 16
0
 def datetime_adapter(obj, request):
     return json_util.default(obj)
Exemplo n.º 17
0
Arquivo: utils.py Projeto: LeslieM/dex
def _custom_json_hook(obj):
    if type(obj) in [datetime, date]:
        return {"$date": obj.strftime("%Y-%m-%dT%H:%M:%S.000Z")}
    else:
        return json_util.default(obj)
Exemplo n.º 18
0
def dict_to_json_converter(obj, **kwargs):
    if isinstance(obj, ObjectId):
        return OID_PREFIX + str(obj)
    else:
        return json_util.default(obj, **kwargs)
Exemplo n.º 19
0
 def objectId_adapter(obj, request):
     return json_util.default(obj)
Exemplo n.º 20
0
def _custom_json_default(obj):
    if is_date_value(obj):
        return datetime_to_bson(obj)
    else:
        return json_util.default(obj)
Exemplo n.º 21
0
 def pymongo_adapter(obj, request):
     return json_util.default(obj)