python – json树中超出了最大递归深度
发布时间:2020-12-20 11:41:34 所属栏目:Python 来源:网络整理
导读:def get_children(node): for child in node['children']: yield child for grandchild in get_children(child): yield grandchildfor line in f: d = json.loads(line) child_dic={} for child in get_children(d): if child not in child_dic.keys(): chil
def get_children(node): for child in node['children']: yield child for grandchild in get_children(child): yield grandchild for line in f: d = json.loads(line) child_dic={} for child in get_children(d): if child not in child_dic.keys(): child_dic[child["id"]]=1 当我用他的代码来查找json树有的孩子数时, 解决方法
你有一棵树的深度超过了998级:
>>> def build_nested(depth): ... d = {'children': []} ... for i in range(depth - 1): ... d['children'].append({'children': []}) ... d = d['children'][0] ... return d ... >>> try: ... len(list(get_children(build_nested(998)))) ... except RuntimeError: ... print 'too deep' ... 997 >>> try: ... len(list(get_children(build_nested(999)))) ... except RuntimeError: ... print 'too deep' ... too deep 在这种情况下不要使用递归.使用堆栈: def get_children(node): stack = [node] while stack: node = stack.pop() stack.extend(node['children'][::-1]) yield node 这个简单的方法首先遍历您的树深度,就像递归版本一样,以相同的顺序遍历. 这仅受您可以为Python提供的内存量的限制: >>> try: ... len(list(get_children(build_nested(999)))) ... except RuntimeError: ... print 'too deep' ... 998 >>> try: ... len(list(get_children(build_nested(10**6)))) ... except RuntimeError: ... print 'too deep' ... 999999 然而,这无助于加载这样的物体; json库也有限制: >>> import json >>> json.loads('{"a":' * 100000 + '1' + '}' * 100000) Traceback (most recent call last): File "<stdin>",line 1,in <module> File "/.../lib/python2.7/json/__init__.py",line 338,in loads return _default_decoder.decode(s) File "/.../lib/python2.7/json/decoder.py",line 366,in decode obj,end = self.raw_decode(s,idx=_w(s,0).end()) File "/.../lib/python2.7/json/decoder.py",line 382,in raw_decode obj,end = self.scan_once(s,idx) RuntimeError: maximum recursion depth exceeded while calling a Python object 您可以尝试使用 我不知道任何其他Python JSON库可以处理您看起来具有如此深度的JSON对象. jsonlib2只是段错误,ujson有1024个对象的硬编码深度限制,而且demjson也给你一个最大的递归深度错误. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |