首页 > 解决方案 > 从模型对象中使用 python 在 json 中创建树

问题描述

我有一个存储模型,我需要从中获取树形式的对象并这样做:

if model == 'Storage':
    if method == 'Read':
        try:
            list_sr = []
            storage = Storage.objects.all()
            for item_sr in list(storage):
                dict_sr = {}
                if item_sr.id_parent_id == 0:
                    dict_sr['text'] = item_sr.name
                    dict_sr['id'] = str(item_sr.id)
                    dict_sr['expanded'] = True
                if item_sr.id_parent_id != 0:
                    dict_sr['children'] = [{'text:' + item_sr.name + ", leaf = True"}]
                list_sr.append(dict_sr)

            result = {'expanded': 'true', 'text': 'Storage', 'children': list_sr}
            jsonFormat = json.dumps(result, indent=4, sort_keys=True, default=str)
            print('Look' + str(jsonFormat))
            ...

字典数据的输出结果显示如下形式:

{
    "children": [
        {
            "expanded": true,
            "id": "9",
            "text": "Title 1"
        },
        {
            "children": [
                "{'text:Test 1, leaf = True'}"
            ]
        },
        {
            "children": [
                "{'text:Test 2, leaf = True'}"
            ]
        },
        {
            "expanded": true,
            "id": "12",
            "text": "Title 2"
        },
        {
            "children": [
                "{'text:Test 3, leaf = True'}"
            ]
        },
        {
            "children": [
                "{'text:Test 4, leaf = True'}"
            ]
        }
    ],
    "expanded": "true",
    "text": "Storage"
}

我需要以这种形式获取数据:

expanded: true, text: "Storage",

children:[

  {
    text: "Title 1", id: '9', expanded: true,
    children: [
    {
        text: "Test 1", leaf: true ,
    },
    {
        text: "Test 2", leaf: true
    }

    ]
 },
 {
    text: "Title 2", id: '12', expanded: true,
    children: [
    {
        text: "Test 3", leaf: true ,
    },
    {
        text: "Test 4", leaf: true
    }

    ]
 }

 ]

在 python 中,我是新手,因此我无法在循环中生成正确的数据,以便它们具有适合 Ext.data.TreeStore 的表示。如何更改循环中的代码以获取正确格式的数据?

标签: pythondjangopython-3.x

解决方案


推荐阅读