问题
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
}
]
}
]
}
How can I return two adjacent levels in Python?
For example return:
a - b,e
f - g,j
The data could become very large, therefore I have to slice it into smaller pieces.
Thanks for every help.
回答1:
You need to build a tree of dicts, 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:
- 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}
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}}}
回答2:
Try this solution, tell me this works or not.
dictVar = {
"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
}
]
}
]
}
name = {}
for dobj in dictVar['children']:
for c in dobj['children']:
if not dobj['name'] in name:
name[dobj['name']] = [c['name']]
else:
name[dobj['name']].append(c['name'])
print(name)
AND as you need all origin data then another is :
name = {}
for dobj in dictVar['children']:
for c in dobj['children']:
if not dobj['name'] in name:
name[dobj['name']] = [c]
else:
name[dobj['name']].append(c)
print(name)
来源:https://stackoverflow.com/questions/53828023/how-can-i-get-certain-levels-of-json-in-python