使用JSON键作为嵌套JSON中的属性

编程入门 行业动态 更新时间:2024-10-27 20:36:15
本文介绍了使用JSON键作为嵌套JSON中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用python 2.7中与类似JSON的嵌套数据结构进行交换,并与一些外国perl代码进行交换.我只想以一种更加Python化的方式使用"列表和字典的这些嵌套结构.

I'm working with nested JSON-like data structures in python 2.7 that I exchange with some foreign perl code. I just want to 'work with' these nested structures of lists and dictionaries in amore pythonic way.

所以,如果我有这样的结构...

So if I have a structure like this...

a = { 'x': 4, 'y': [2, 3, { 'a': 55, 'b': 66 }], }

...我希望能够在python脚本中处理它,就像它是嵌套的python类/结构一样,

...I want to be able to deal with it in a python script as if it was nested python classes/Structs, like this:

>>> 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是原始结构的代理.到目前为止,我的灵感来自出色的 ?问题.

Thus aa is a proxy into the original structure. This is what I came up with so far, inspired by the excellent What is a metaclass in Python? question.

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内容.

Now I wonder whether there is an elegant way of mapping a whole set of the __*__ special functions, like __iter__, __delitem__? so I don't need to unwrap things using p2j() just to iterate or do other pythonic stuff.

# today: for i in p2j(aa.y): print i # would like to... for i in aa.y: print i

推荐答案

有一个attrdict库以一种非常安全的方式完全做到了这一点,但是如果您愿意,可以在此答案:

There is an attrdict library that does exactly that in a very safe manner, but if you want, a quick and dirty (possibly leaking memory) approach was given in this answer:

class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self j = '{"y": [2, 3, {"a": 55, "b": 66}], "x": 4}' aa = json.loads(j, object_hook=AttrDict)

更多推荐

使用JSON键作为嵌套JSON中的属性

本文发布于:2023-11-14 16:29:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587957.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   属性   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!