반응형
Python 직렬화 가능 개체 json
class gpagelet:
"""
Holds 1) the pagelet xpath, which is a string
2) the list of pagelet shingles, list
"""
def __init__(self, parent):
if not isinstance( parent, gwebpage):
raise Exception("Parent must be an instance of gwebpage")
self.parent = parent # This must be a gwebpage instance
self.xpath = None # String
self.visibleShingles = [] # list of tuples
self.invisibleShingles = [] # list of tuples
self.urls = [] # list of string
class gwebpage:
"""
Holds all the datastructure after the results have been parsed
holds: 1) lists of gpagelets
2) loc, string, location of the file that represents it
"""
def __init__(self, url):
self.url = url # Str
self.netloc = False # Str
self.gpagelets = [] # gpagelets instance
self.page_key = "" # str
클래스 json을 연재할 수 있는 방법이 있나요?제가 걱정하는 것은 재귀 참조입니다.
독자적인 인코더와 디코더를 작성할 수 있습니다.이것은 다음과 같이 매우 심플합니다.return __dict__
예를 들어, 여기에는 완전히 재귀적인 트리 구조를 덤프하기 위한 인코더가 있으며, 이를 강화하거나 자신의 목적을 위해 그대로 사용할 수 있습니다.
import json
class Tree(object):
def __init__(self, name, childTrees=None):
self.name = name
if childTrees is None:
childTrees = []
self.childTrees = childTrees
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if not isinstance(obj, Tree):
return super(MyEncoder, self).default(obj)
return obj.__dict__
c1 = Tree("c1")
c2 = Tree("c2")
t = Tree("t",[c1,c2])
print json.dumps(t, cls=MyEncoder)
인쇄하다
{"childTrees": [{"childTrees": [], "name": "c1"}, {"childTrees": [], "name": "c2"}], "name": "t"}
마찬가지로 디코더를 작성할 수 있지만, 어떤 식으로든 그것이 대상인지 아닌지를 식별할 필요가 있기 때문에, 필요에 따라서 타입도 입력할 수 있습니다.
간접답변: JSON을 사용하는 대신 YAML을 사용할 수 있어 원하는 작업을 하는 데 문제가 없습니다.(JSON은 기본적으로 YAML의 서브셋입니다).
예:
import yaml
o1 = gwebpage("url")
o2 = gpagelet(o1)
o1.gpagelets = [o2]
print yaml.dump(o1)
실제로 YAML은 순환 참조를 적절하게 처리합니다.
매우 간단한 시스템을 구현했습니다.todict
https://stackoverflow.com/a/11637457/1766716의 도움을 받아 메서드를 만듭니다.
- 다음 문자로 시작하지 않은 속성에 대해 반복
__
- 메서드 배제
- 필요하지 않은 일부 속성을 수동으로 삭제(내 경우 sqalcemy에서 가져온다)
그리고 사용.getattr
사전을 구축합니다.
class User(Base):
id = Column(Integer, primary_key=True)
firstname = Column(String(50))
lastname = Column(String(50))
password = Column(String(20))
def props(self):
return filter(
lambda a:
not a.startswith('__')
and a not in ['_decl_class_registry', '_sa_instance_state', '_sa_class_manager', 'metadata']
and not callable(getattr(self, a)),
dir(self))
def todict(self):
return {k: self.__getattribute__(k) for k in self.props()}
이를 위한 솔루션으로는 init, update 및 set class 메서드를 덮어쓰고 'dict' 클래스를 확장하고 필수/허용 속성을 체크하는 것이 있었습니다.
class StrictDict(dict):
required=set()
at_least_one_required=set()
cannot_coexist=set()
allowed=set()
def __init__(self, iterable={}, **kwargs):
super(StrictDict, self).__init__({})
keys = set(iterable.keys()).union(set(kwargs.keys()))
if not keys.issuperset(self.required):
msg = str(self.__class__.__name__) + " requires: " + str([str(key) for key in self.required])
raise AttributeError(msg)
if len(list(self.at_least_one_required)) and len(list(keys.intersection(self.at_least_one_required))) < 1:
msg = str(self.__class__.__name__) + " requires at least one: " + str([str(key) for key in self.at_least_one_required])
raise AttributeError(msg)
for key, val in iterable.iteritems():
self.__setitem__(key, val)
for key, val in kwargs.iteritems():
self.__setitem__(key, val)
def update(self, E=None, **F):
for key, val in E.iteritems():
self.__setitem__(key, val)
for key, val in F.iteritems():
self.__setitem__(key, val)
super(StrictDict, self).update({})
def __setitem__(self, key, value):
all_allowed = self.allowed.union(self.required).union(self.at_least_one_required).union(self.cannot_coexist)
if key not in list(all_allowed):
msg = str(self.__class__.__name__) + " does not allow member '" + key + "'"
raise AttributeError(msg)
if key in list(self.cannot_coexist):
for item in list(self.cannot_coexist):
if key != item and item in self.keys():
msg = str(self.__class__.__name__) + "does not allow members '" + key + "' and '" + item + "' to coexist'"
raise AttributeError(msg)
super(StrictDict, self).__setitem__(key, value)
사용 예:
class JSONDoc(StrictDict):
"""
Class corresponding to JSON API top-level document structure
http://jsonapi.org/format/#document-top-level
"""
at_least_one_required={'data', 'errors', 'meta'}
allowed={"jsonapi", "links", "included"}
cannot_coexist={"data", "errors"}
def __setitem__(self, key, value):
if key == "included" and "data" not in self.keys():
msg = str(self.__class__.__name__) + " does not allow 'included' member if 'data' member is not present"
raise AttributeError(msg)
super(JSONDoc, self).__setitem__(key, value)
json_doc = JSONDoc(
data={
"id": 5,
"type": "movies"
},
links={
"self": "http://url.com"
}
)
언급URL : https://stackoverflow.com/questions/1458450/python-serializable-objects-json
반응형
'programing' 카테고리의 다른 글
쿼리 문자열에서 매개 변수 값을 가져오려면 어떻게 해야 합니까? (0) | 2023.03.18 |
---|---|
UI 선택에서 수동으로 입력한 텍스트 허용 (0) | 2023.03.18 |
mock inner axios.create() (0) | 2023.03.18 |
React 컴포넌트가 재렌더되는 이유를 추적 (0) | 2023.03.18 |
this.setState가 예상대로 상태를 Marge하지 않습니다. (0) | 2023.03.13 |