在python中遍历json树时保持子和父关系

时间:2015-08-20 13:51:48

标签: python json

我有一个

形式的json树
List<RestModels.Response.RealWorkOrder> RWOList = _context.MOB_WORKORDERS_SUMMARY
            .Where(mws => _context.TBL_USER_GROUP_MEMBERS.Any(u => u.user_Id == UserID && u.user_Group_Id == mws.user_group_id))// && !disallowedStatuses.Contains(mws.workorder_status_id ?? -1))
            .Select(mob => _context.FMIS_WORKORDER.FirstOrDefault(wo => wo.workorder_id == mob.workorder_id))
             //// added below line to get the category item in one go
            .Select(tempLet => new {workOrder = tempLet, CategoryItem = _context.VIEW_WORK_CATEGORIES.Where(cat => cat.work_category_id == tempLet.FMIS_WORKREQUEST1.FirstOrDefault().workrequest_category).FirstOrDefault()})
            .Select(wo =>
        new RestModels.Response.RealWorkOrder()
        {
            AssetLocation = wo.workOrder.FMIS_ASSET_LOCATION.asset_location_description,
            IAssets = wo.workOrder.FMIS_WORKORDER_ASSETS.Select(woa => new RestModels.Subclasses.Asset()
            {
                AssetId = woa.FMIS_ASSET.asset_id,
                AssetName = woa.FMIS_ASSET.asset_title + " - " + woa.FMIS_ASSET.asset_description,
                SerialNumber = woa.FMIS_ASSET.asset_UF_1
            }),
            ...

            CategoryDescription = wo.CategoryItem.work_category_title + " - " +
                wo.CategoryItem.work_category_description + " [" +
                wo.CategoryItem.work_category_priority_name + "]",

对于每个节点,我想保留一个具有的结构     {"reply": 0, "id": 457, "children": [{"reply": 1, "id": 463, "children": [{"reply": 1, "id": 461, "children": [{"reply": 1, "id": 464, "children": [{"reply": 1, "id": 467, "children": []}]}]}]}, {"reply": 0, "id": 457, "children": []}]}

e.g {node id,parent id,(immediate children of the node) {457, none,(463,457)} {463,457,(461)} 等等。 我可以保留孩子的数量,但不知道如何保留父ID。

{461,463,(464)}

2 个答案:

答案 0 :(得分:0)

您可以在树上执行搜索,跟踪父级:

from collections import deque

def generate_children(tree):
    queue = deque()
    queue.append((tree, None))

    while queue:
        node, parent = queue.pop()
        children = []
        for child in node['children']:
            queue.append((child, node['id']))
            children.append(child['id'])
        yield node['id'], parent, children

如果上面的数据位于名为tree的变量中,则代码为:

>>> list(generate_children(tree))
[(457, None, [463, 457]),
 (457, 457, []),
 (463, 457, [461]),
 (461, 463, [464]),
 (464, 461, [467]),
 (467, 464, [])]

答案 1 :(得分:0)

如果您只需要保留父ID以及子ID,您可以尝试:

def get_children(d, parent=None, l = []):
    print (d['id'], parent, len(d['children']))
    l.append( (d['id'], parent))
    for child in d['children']:
        get_children(child, d['id'], l)
    return l

你得到:

>>> l = get_children(tree)
457 None 2
463 457 1
461 463 1
464 461 1
467 464 0
458 457 0
>>> l
[(457, None), (463, 457), (461, 463), (464, 461), (467, 464), (458, 457)]