我正在與python 2.7中的嵌套類JSON數據結構一起工作,這些數據結構與一些外部Perl代碼交換。我只想以'amore pythonic'的方式與這些嵌套的列表和詞典結構一起工作。在嵌套JSON中使用JSON鍵作爲屬性
所以,如果我有這樣的結構...
a = {
'x': 4,
'y': [2, 3, { 'a': 55, 'b': 66 }],
}
...我希望能夠在Python腳本來處理它,如果它是嵌套的Python類/的Structs,這樣:
>>> aa = j2p(a) # <<- this is what I'm after.
>>> print aa.x
4
>>> aa.z = 99
>>> print a
{
'x': 4,
'y': [2, 3, { 'a': 55, 'b': 66 }],
'z': 99
}
>>> aa.y[2].b = 999
>>> print a
{
'x': 4,
'y': [2, 3, { 'a': 55, 'b': 999 }],
'z': 99
}
因此,aa是原始結構的代理。這是我迄今爲止提出的,受到優秀What is a metaclass in Python?問題的啓發。
def j2p(x):
"""j2p creates a pythonic interface to nested arrays and
dictionaries, as returned by json readers.
>>> a = { 'x':[5,8], 'y':5}
>>> aa = j2p(a)
>>> aa.y=7
>>> print a
{'x': [5, 8], 'y':7}
>>> aa.x[1]=99
>>> print a
{'x': [5, 99], 'y':7}
>>> aa.x[0] = {'g':5, 'h':9}
>>> print a
{'x': [ {'g':5, 'h':9} , 99], 'y':7}
>>> print aa.x[0].g
5
"""
if isinstance(x, list):
return _list_proxy(x)
elif isinstance(x, dict):
return _dict_proxy(x)
else:
return x
class _list_proxy(object):
def __init__(self, proxied_list):
object.__setattr__(self, 'data', proxied_list)
def __getitem__(self, a):
return j2p(object.__getattribute__(self, 'data').__getitem__(a))
def __setitem__(self, a, v):
return object.__getattribute__(self, 'data').__setitem__(a, v)
class _dict_proxy(_list_proxy):
def __init__(self, proxied_dict):
_list_proxy.__init__(self, proxied_dict)
def __getattribute__(self, a):
return j2p(object.__getattribute__(self, 'data').__getitem__(a))
def __setattr__(self, a, v):
return object.__getattribute__(self, 'data').__setitem__(a, v)
def p2j(x):
"""p2j gives back the underlying json-ic json-ic nested
dictionary/list structure of an object or attribute created with
j2p.
"""
if isinstance(x, (_list_proxy, _dict_proxy)):
return object.__getattribute__(x, 'data')
else:
return x
現在我不知道是否有映射一整套的__*__
特殊功能的一個優雅的方式,像__iter__
,__delitem__
?所以我不需要使用p2j()
來解開東西來迭代或執行其他pythonic東西。
# today:
for i in p2j(aa.y):
print i
# would like to...
for i in aa.y:
print i
我認爲你正在尋找此解決方案 - http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python#answer-14620633 – Yurik 2014-08-14 22:27:00