def default(self, obj): if isinstance(obj, User): dic={'login':obj.login,'p':obj.p,'name':obj.name,'logged':obj.logged} return dic if isinstance(obj, Repository): dic={'org':obj.org,'name':obj.name,'directory':obj.directory,'json_exists':obj.json_exists,'exists':obj.exists,'content':obj.content,'file_name':obj.file_name} return dic else: JSONEncoder.default(self, obj)
def default(self, obj): if isinstance(obj, date): return dateutil.simple_format_date(obj) elif isinstance(obj, datetime): return dateutil.simple_format_datetime(obj) elif isinstance(obj, Iterable) and not isinstance(obj, (dict, list, set)): # 这个实现可能有问题 return JSONEncoder.default(self, list(obj)) return JSONEncoder.default(self, obj)
def default(self, obj): from datatypes import User app.logger.debug("running custom jsonencoder") if isinstance(obj, User): # Implement code to convert Passport object to a dict user_dict = {"name": obj.displayName(), "userID": obj.userID, "isAdmin": obj.isAdmin, "isMCRMember": obj.isMCRMember, "isAssociateMember": obj.isAssociateMember, "isCRA": obj.isCRA, "isCollegeBill": obj.isCollegeBill} return user_dict else: JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, date): return JSONEncoder.default( self, datetime(obj.year, obj.month, obj.day)) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() millis = int( calendar.timegm(obj.timetuple()) * 1000 + obj.microsecond / 1000 ) return millis if isinstance(obj, date): millis = int( calendar.timegm(obj.timetuple()) * 1000 ) return millis if isinstance(obj, np.int64): val = int(obj) return val iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, datetime): return serialize_datatime(obj) except TypeError: pass return JSONEncoder.default(self, obj)
def default(self, o): if isinstance(o, PersistentID): return o.hex elif isinstance(o, Enum): return o.name else: return FlaskJSONEncoder.default(self, o)
def default(self, obj): if isinstance(obj, Character): return obj.__dict__ elif isinstance(obj, Weapon): return obj.__dict__ else: return JSONEncoder.default(self, obj)
def default(self, obj): if isinstance(obj, ObjectId): return json_util.dumps(obj) elif isinstance(obj, datetime.datetime): return calendar.timegm(obj.utctimetuple())*1000 else: return JSONEncoder.default(self, obj)
def default(self, obj): if isinstance(obj, datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() return str(obj) else: return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() millis = int( calendar.timegm(obj.timetuple()) * 1000 + obj.microsecond / 1000 ) return millis if isinstance(obj, sqlalchemy.orm.state.InstanceState): return "" if isinstance(obj, ScannerStatistic): return "" if isinstance(obj, ScannerLocation): return "" iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, o): if isinstance(o, Segment): return { 'id': o.id, 'text_id': o.text_id, 'slug': o.slug, 'content': xml_transform(o.content), } elif isinstance(o, Text): return { 'id': o.id, 'name': o.name, 'slug': o.slug, 'xmlid_prefix': o.xmlid_prefix } elif isinstance(o, Card): return { 'primary': self.default(o.primary), 'translations': [self.default(x) for x in o.translations], 'commentaries': [self.default(x) for x in o.commentaries], } elif isinstance(o, ChildCard): return { 'text_id': o.text_id, 'segments': [self.default(x) for x in o.segments], } return JSONEncoder.default(self, o)
def default(self, o): # pylint: disable=method-hidden """Convert unserializable types for JSON encoding.""" if isinstance(o, datetime): # Stuffr uses ISO dates return o.isoformat() return JSONEncoder.default(self, o)
def default(self, obj): if hasattr(obj, 'to_json') and hasattr(obj.to_json, '__call__'): return obj.to_json() if isinstance(obj, datetime): return obj.isoformat() if isinstance(obj, int) and obj >= (1 << 31): return str(obj) return JSONEncoder.default(self, obj)
def default(self, o): if hasattr(o, '__getitem__') and hasattr(o, 'keys'): return dict(o) if isinstance(o ,datetime.datetime): return o.strftime('%Y-%m-%d %H:%M:%S') return _JSONEncoder.default(self, o)
def default(self, o): if isinstance(o, datetime.date): if isinstance(o, datetime.datetime): return str(o.replace(microsecond=0)) return str(o) if hasattr(o, 'as_dict'): return o.as_dict() return JSONEncoder.default(self, o)
def default(self, obj): try: if isinstance(obj, Activity): return obj.serialize() except TypeError: pass else: return JSONEncoder.default(self, obj)
def default(self, obj): if hasattr(obj, '__getitem__') and hasattr(obj, 'keys'): return dict(obj) if isinstance(obj, datetime.datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') if isinstance(obj, ObjectId): return str(obj) return _JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, Decimal): if obj % 2 in (Decimal(0), Decimal(1)): return int(obj) return float(obj) except TypeError: pass return JSONEncoder.default(self, obj)
def default(self, obj): if isinstance(obj, Workflow): return self._workflow_to_dict(obj) elif isinstance(obj, logging.LogRecord): return self._logrecord_to_dict(obj) elif isinstance(obj, Event): return self._event_to_dict(obj) else: return JSONEncoder.default(self, obj)
def default(self, o): if isinstance(o, time.struct_time): return "{}/{}/{} {}:{}:{}".format(o.tm_mon, o.tm_mday, o.tm_year, o.tm_hour, o.tm_min, o.tm_sec) return JSONEncoder.default(self, o)
def default(self, obj): try: if isinstance(obj, datetime.date): return obj.isoformat() except TypeError: pass #else: # return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): if isinstance(obj, ndb.Key): return obj.id() elif isinstance(obj, ndb.Model): # call model's to_dict() and tack on the id as well return dict(obj.to_dict(), **dict(id=obj.key.id())) elif isinstance(obj, (datetime, date, time)): return str(obj) # todo: make sure this is what we want return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, datetime): return int(time.mktime(obj.timetuple())) * 1000 + obj.microsecond / 1000 iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, Enum): return obj.value iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, Mol): return MolToMolBlock(obj) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, Arrow): return obj.timestamp iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, o): try: if isinstance(o, datetime): return o.strftime("%Y-%m-%dT%H:%M:%S%z") iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o)
def default(self, obj): try: if isinstance(obj, datetime): return obj.strftime("%Y/%m/%d") iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, Email): return obj.to_json() iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() millis = int( calendar.timegm(obj.timetuple()) * 1000 + obj.microsecond / 1000) return millis iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): import decimal import datetime try: if isinstance(obj, datetime.date): return obj.isoformat(sep=' ') if isinstance(obj, datetime.datetime): return obj.isoformat(sep=' ') if isinstance(obj, decimal.Decimal): return float(obj) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): if isinstance(obj, FileEntry): return obj.to_json() if isinstance(obj, Task): return { 'guid': obj.guid, 'files': list(obj.files.keys()), 'time': obj.time } try: iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): # pylint: disable=E0202, W0221 try: if isinstance(obj, datetime): return obj.strftime('%a, %-d %b %Y %H:%M:%S') if isinstance(obj, timedelta): seconds = obj.total_seconds() hours = seconds // 3600 minutes = (seconds % 3600) // 60 seconds = seconds % 60 return "%02d:%02d:%.2f" % (hours, minutes, seconds) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, o): try: if isinstance(o, datetime): return o.isoformat() if isinstance(o, MxStatus): return o.to_json() if isinstance(o, MxLogPage): return o.to_json() if isinstance(o, FxStatus): return o.to_json() iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o)
def default(self, obj): if hasattr(obj, 'get_dict'): return obj.get_dict() elif hasattr(obj, 'serialize'): return obj.serialize() try: return JSONEncoder.default(self, obj) except TypeError: print('Unserialized') print('class', obj.__class__) print('bases', dir(obj)) print(type(obj)) return {'__{}__'.format(obj.__class__.__name__): obj.__dict__}
def add(): planeta = mongo.db.planeta nome = request.json['nome'] clima = request.json['clima'] terreno = request.json['terreno'] planeta_id = planeta.insert({ 'nome': nome, 'clima': clima, 'terreno': terreno }) p = planeta.find_one({'_id': planeta_id}) output = JSONEncoder().encode(p) return output
def default(self, obj): try: if isinstance(obj, datetime.datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() return obj.isoformat().__str__() elif isinstance(obj, datetime.date): return obj.isoformat().__str__() else: return obj.__dict__ except TypeError: pass else: iterable = iter(obj) return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): if isinstance(obj, ObjectId): return str(obj) elif isinstance(obj, bytes): return str(obj, 'utf-8') elif isinstance(obj, Cursor): return [self.default(i) for i in obj] elif isinstance(obj, Decimal128): return obj.to_decimal() elif isinstance(obj, Decimal): return float(obj) elif isinstance(obj, (datetime, date)): return obj.strftime(DATETIME_FORMAT) elif isinstance(obj, DBRef): return str(obj.id) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, datetime): ts = int(obj.timestamp()) if ts < 0: ts = 0 return ts if isinstance(obj, float): return round(obj, 3) iterable = iter(obj) except TypeError: traceback.print_exc() pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): if hasattr(obj, "serialize"): return obj.serialize() try: if isinstance(obj, datetime.date) or isinstance(obj, datetime.datetime): return obj.isoformat() if isinstance(obj, Decimal): return str(obj) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, o): """ :param o: """ if isinstance(o, set): return list(o) if isinstance(o, bytes): try: # Try unicode return o.decode() except UnicodeDecodeError: # Otherwise, base64 return b64encode(o).decode() if isinstance(o, UserString): return str(o) return JSONEncoder.default(self, o)
def default(self, obj): try: if isinstance(obj, datetime.date): return obj.isoformat() + "Z" elif isinstance(obj, BaseDocument): return obj.to_mongo(use_db_field=False) elif isinstance(obj, QuerySet): return list(obj) elif isinstance(obj, ObjectId): return str(obj) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, datetime): # python does not really conform to ISO 8601 # it is not tz aware unless the TZ is explicitly set serial = dtu.localizeToTz(obj).isoformat() return serial elif isinstance(obj, ObjectId): serial = str(obj) return serial iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): if hasattr(obj, 'to_dict'): return obj.to_dict() elif isinstance(obj, Workflow): return self._workflow_to_dict(obj) elif isinstance(obj, logging.LogRecord): return self._logrecord_to_dict(obj) elif isinstance(obj, Event): return self._event_to_dict(obj) elif isinstance(obj, Path): return mimetypes.guess_type(unicode(obj))[0] elif isinstance(obj, datetime): # Return datetime as an epoch timestamp with microsecond-resolution return (time.mktime(obj.timetuple())*1000 + obj.microsecond)/1000.0 else: return JSONEncoder.default(self, obj)
def default(self, obj): if isinstance(obj, decimal.Decimal): # wanted a simple yield str(o) in the next line, # but that would mean a yield on the line with super(...), # which wouldn't work (see my comment below), so... return (str(obj) for obj in [obj]) try: if isinstance(obj, date): return obj.isoformat() iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, o): if isinstance(o, custom_types): data = dict() keys = [_ for _ in dir(o) if not _.startswith('_')] for key in keys: value = getattr(o, key) if not isinstance(value, all_types): continue data[key] = value return data elif isinstance(o, enum_types): return str(o.name) return FlaskJSONEncoder.default(self, o)
def default(self, obj): try: if isinstance(obj, date): result = obj.strftime( "%a, %d %B %Y %H:%M" ) # https://docs.python.org/3/library/datetime.html return result if isinstance(obj, decimal.Decimal ): # Allows the database to return bigint values. return int(obj) iterable = iter(obj) except TypeError as e: print(e) pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() # elif tf.is_tensor(obj): # return list(np.array(obj)) print(obj) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, date): return obj.isoformat() if isinstance(obj, datetime.datetime): print("捕捉到了datetime异常") return obj.strftime("%Y-%m-%d %H:%M:%S") if isinstance(obj, decimal.Decimal): return float(obj) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: get_encodable = getattr(obj, 'get_encodable', None) if callable(get_encodable): return get_encodable() if isinstance(obj, datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() return obj.isoformat() if isinstance(obj, ObjectId): return str(obj) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, np.ndarray): return obj.tolist() elif obj is None: return 'null' iterable = iter(obj) except TypeError: pass else: return list(iterable) try: result = JSONEncoder.default(self, obj) except: result = str(obj) return result
def default(self, obj): if isinstance(obj, np.int32) or isinstance(obj, np.int64): return int(obj) if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): return int(obj) if isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): return float(obj) if isinstance(obj, (np.ndarray, )): return obj.tolist() # Let the base class default method raise the TypeError return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, datetime.datetime): if obj.strftime('%Y-%m-%d %H:%M:%S') == '1970-01-01 00:00:00': return '' return obj.strftime('%Y-%m-%d %H:%M:%S') if isinstance(obj, datetime.date): if obj.strftime('%Y-%m-%d') == '1970-01-01': return '' return obj.strftime('%Y-%m-%d') if isinstance(obj, Decimal): return str(obj) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, datetime): return obj.isoformat() if isinstance(obj, WKBElement): shp_obj = to_shape(obj) if shp_obj.geom_type == "Point": return shp_obj.coords if shp_obj.geom_type == "Polygon": return shp_obj.exterior.coords else: return None iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() delta = obj - EPOCH if self._get_api_version() in ["v1", None]: millis = int(delta.total_seconds()) else: millis = int(delta.total_seconds() * 1000) return millis iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
def default(self, obj): try: if isinstance(obj, datetime): # if obj.utcoffset() is not None: # obj = obj - obj.utcoffset() return obj.astimezone(timezone('Asia/Bangkok')).isoformat() if isinstance(obj, date): return str(obj.isoformat()) if isinstance(obj, Decimal): return str(obj) if isinstance(obj, enum.Enum): return str(obj.value) if isinstance(obj, time): return str(obj) iterable = iter(obj) except TypeError: pass return JSONEncoder.default(self, obj)
def default(self, obj): if isinstance(obj, User.User): return { 'uid': obj.uid, 'username': obj.username, 'encoding': obj.encoding } elif isinstance(obj, Book.Book): return { 'book_id': obj.book_id, 'name': obj.name, 'lent': obj.lent, 'borrower': obj.borrower, 'time': obj.time } else: print(obj) return JSONEncoder.default(self, obj)
def get_all_mongo(): planeta = mongo.db.planeta result = [] mensagem = {'Erro': 'Nenhum planeta encontrado'} #MONGODB for p in planeta.find(): result.append({ '_id': JSONEncoder().encode(p['_id']), 'nome': p['nome'], 'clima': p['clima'], 'terreno': p['terreno'], 'quantidade de aparições em filmes: ': 0 }) if len(result) == 0: return mensagem else: return result
def default(self, obj): if isinstance(obj, db.Model): return obj.json() if isinstance(obj, dt): #return o.strftime("%Y-%m-%d %H:%M:%S") return obj.strftime("%d-%m-%Y") if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): return int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): return float(obj) elif isinstance(obj, (np.ndarray, )): #### This is the fix return obj.tolist() return JSONEncoder.default(self, obj)