How can I get certain levels of JSON in Python?

故事扮演 提交于 2020-01-06 07:54:12

问题


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:

  1. get the "name" of a node for use as a key
  2. if the node has "children", transform them to a dict
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!