遍历json对象中的所有项目 [英] Iterate over all items in json object
问题描述
通过data = json.load(fp)
从文件加载json之后,我要遍历json中的所有项目,当然不包括所有特殊的Python符号.
如何正确完成?
After loading json from a file via data = json.load(fp)
I want to iterate over all items that were in json, excluding of course all special Python symbols.
How is this done properly?
推荐答案
data
在这一点上应该是普通的集合,因此您可以像遍历任何其他列表/dict/一样对它进行迭代.任何.它来自load
的事实不会对您造成任何额外的要求.
data
should be an ordinary collection at this point, so you'd iterate over it the same way you'd iterate over any other list/dict/whatever. The fact that it came from load
doesn't incur any extra requirements on your part.
下面是一个使用loads
的示例,该示例在原理上相似:
Here's an example that uses loads
, which is similar in principle:
import json
my_json_data = "[1,2,3]"
data = json.loads(my_json_data)
for item in data:
print(item)
结果:
1
2
3
如果您问如何遍历数据中的所有值,包括深度嵌套集合中包含的值?",则可以执行以下操作:>
import json
my_json_data = """[
1,
{
"2": 3,
"4": [
"5",
"6",
"7"
]
},
8,
9
]"""
def recursive_iter(obj):
if isinstance(obj, dict):
for item in obj.values():
yield from recursive_iter(item)
elif any(isinstance(obj, t) for t in (list, tuple)):
for item in obj:
yield from recursive_iter(item)
else:
yield obj
data = json.loads(my_json_data)
for item in recursive_iter(data):
print(item)
结果:
1
5
6
7
3
8
9
通过递归调用,并在传递给集合时添加新的键,您还可以跟踪导航到每个值所需的键.
You can also keep track of the keys needed to navigate to each value, by passing them through the recursive calls and adding new keys to the collection as you pass over them.
def recursive_iter(obj, keys=()):
if isinstance(obj, dict):
for k, v in obj.items():
yield from recursive_iter(v, keys + (k,))
elif any(isinstance(obj, t) for t in (list, tuple)):
for idx, item in enumerate(obj):
yield from recursive_iter(item, keys + (idx,))
else:
yield keys, obj
data = json.loads(my_json_data)
for keys, item in recursive_iter(data):
print(keys, item)
结果:
(0,) 1
(1, '2') 3
(1, '4', 0) 5
(1, '4', 1) 6
(1, '4', 2) 7
(2,) 8
(3,) 9
这篇关于遍历json对象中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!