簡體   English   中英

使用Python中的繼承屬性展平嵌套的JSON數組

[英]Flatten nested JSON arrays with inherits properties in Python

我有一個很大的json / dictionary,具有不同級別的嵌套json數組,我想將其展平,並捕獲結構的關系,

我的json的一部分看起來像:

 { "name": "root", "type": "all", "children": [ { "name": "properties", "type": "feature", "children": [ { "name": "print", "type": "feature", "children": [ { "name": "graphic print", "type": "feature", "inherits": true }, { "name": "striped print", "type": "feature", "inherits": true, "children": [ { "name": "pinstriped", "type": "feature", "inherits": true }, { "name": "light stripe", "type": "feature", "inherits": true }, { "name": "wide stripe", "type": "feature", "inherits": true } ] } ] } ] }, { "name": "colours", "type": "colour", "children": [ { "name": "main colours", "type": "colour", "children": [ { "name": "black", "type": "colour", "children": [ { "name": "light black", "type": "colour", "inherits": true }, { "name": "blue black", "type": "colour", "inherits": true } ] }, { "name": "red", "type": "colour", "children": [ { "name": "bright red", "type": "colour", "inherits": true }, { "name": "light red", "type": "colour" } ] } ] } ] }, { "name": "genders", "type": "gender", "children": [ { "name": "female", "type": "gender" }, { "name": "male", "type": "gender" } ] } ] } 

巢的深度不盡相同。 我-希望所有節點(“名稱”的值)-如果該節點具有“真”值的“繼承”鍵,也希望其所有父節點。

就像是:

在此處輸入圖片說明

但是,如果對如何存儲此數據有更好的想法,也將很樂意接受!

非常感謝!

我認為這應該滿足您的需求

def parse_dict_of_dict(_dict, _parent = '', ret_dict={}):
    _name, _children, _inherit = _dict["name"], _dict.get('children', None), _dict.get('inherits', False)
    if _children is not None:
        if isinstance(_children, list):
            for _child in _children:
                parse_dict_of_dict(_child, _name+ ', ' + _parent if _inherit else _name , ret_dict)
    ret_dict[ _name] = _parent.strip(' ').strip(',') if _inherit else None
    return ret_dict

您能否詳細說明您的輸出?

或者,您可以使用此函數將嵌套JSON展平為簡單JSON。

def parse_dict_of_dict(_dict, _str = ''):
    ret_dict = {}
    for k, v in _dict.iteritems():
        if isinstance(v, dict):
            ret_dict.update(parse_dict_of_dict(v, _str= _str+k+'_'))
        elif isinstance(v, list):
            for index, item in enumerate(v):
                if isinstance(item, dict):
                    ret_dict.update(parse_dict_of_dict(item,  _str=_str+k+'_%d_'%(index)))
                else:
                    ret_dict.update({k+'_%d'%(index): item})
        else:
            try:
                ret_dict[_str + k] = str(v)
            except Exception as e:
                ret_dict[_str + k] = unicode.encode(v, errors='ignore')
    return ret_dict

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM