如何在Python中获得特定级别的JSON? [英] How can I get certain levels of JSON in Python?
本文介绍了如何在Python中获得特定级别的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我的JSON数据如下所示:
If my JSON data looks like this:
{
"name": "root",
"children": [
{
"name": "a",
"children": [
{
"name": "b",
"children": [
{
"name": "c",
"size": "1"
},
{
"name": "d",
"size": "2"
}
]
},
{
"name": "e",
"size": 3
}
]
},
{
"name": "f",
"children": [
{
"name": "g",
"children": [
{
"name": "h",
"size": "1"
},
{
"name": "i",
"size": "2"
}
]
},
{
"name": "j",
"size": 5
}
]
}
]
}
如何在Python中返回两个相邻的级别?
How can I return two adjacent levels in Python?
例如返回:
a-b,e
f-g,j
For example return:
a - b,e
f - g,j
数据可能会变得非常大,因此我必须将其切成小块.
The data could become very large, therefore I have to slice it into smaller pieces.
感谢您的帮助.
推荐答案
您需要构建一棵dict
s的树,其值作为叶子:
You need to build a tree of dict
s, with values as the leaves:
{'a': {'b': {'c': '1', 'd': '2'}, 'e': '3'}, 'f': {'g': {'h': '1', 'i': '2'}, 'j': '5'}}
这可以分解为三个独立的动作:
This can be decomposed into three separate actions:
- 获取节点的
"name"
作为键 - 如果节点具有
"children"
,请将其转换为dict
- 如果节点具有
"size"
,则将其转换为单个值
- get the
"name"
of a node for use as a key - if the node has
"children"
, transform them to adict
- if the node has a
"size"
, transform that to the single value
除非您的数据是深层嵌套的,否则递归是一种简单的方法:
Unless your data is deeply nested, recursion is a straightforward approach:
def compress(node: dict) -> dict:
name = node['name'] # get the name
try:
children = node['children'] # get the children...
except KeyError:
return {name: node['size']} # or return name and value
else:
data = {}
for child in children: # collect and compress all children
data.update(compress(child))
return {name: data}
这将压缩整个层次结构,包括"root"
节点:
This compresses the entire hierarchy, including the "root"
node:
>>> compress(data)
{'root': {'a': {'b': {'c': '1', 'd': '2'}, 'e': 3},
'f': {'g': {'h': '1', 'i': '2'}, 'j': 5}}}
这篇关于如何在Python中获得特定级别的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文