搜索

首页  >  问答  >  正文

tree - 利用python如何将无限分类结构的数据,转换成json格式数据。

id text pid

1 My Documents 0
2 photos 1
3 Friend 2
4 Wife 2
5 Company 2
6 Program Files 1
7 Intel 6
8 Java 6

数据库中是以上结构,如何写段代码生成如下结构的json数据?

[{

"id":1,
"text":"My Documents",
"children":[{
    "id":2,
    "text":"Photos",
    "children":[{
        "id":3,
        "text":"Friend"
    },{
        "id":4,
        "text":"Wife"
    },{
        "id":5,
        "text":"Company"
    }]
},{
    "id":6,
    "text":"Program Files",
    "children":[{
        "id":7,
        "text":"Intel"
    },{
        "id":8,
        "text":"Java",
    }]
}]

}]

PHP中文网PHP中文网2784 天前1116

全部回复(1)我来回复

  • 巴扎黑

    巴扎黑2017-04-18 10:25:45

    import json
    source=[
        {"name":"my document","id":1 , "parentid": 0 },
        {"name":"photos","id":2 , "parentid": 1 },
        {"name":"Friend","id":3 , "parentid": 2 },
        {"name":"Wife","id":4 , "parentid": 2 },
        {"name":"Company","id":5 , "parentid": 2 },
        {"name":"Program Files","id":6 , "parentid": 1 },
        {"name":"intel","id":7 , "parentid": 6 },
        {"name":"java","id":8 , "parentid": 6 },
    ]
    
    def getChildren(id=0):
        sz=[]
        for obj in source:
            if obj["parentid"] ==id:
                sz.append({"id":obj["id"],"text":obj["name"],"children":getChildren(obj["id"])})
        return sz
    
    print json.dumps(getChildren())
    [
      {
        "text": "my document",
        "id": 1,
        "children": [
          {
            "text": "photos",
            "id": 2,
            "children": [
              {
                "text": "Friend",
                "id": 3,
                "children": [ ]
              },
              {
                "text": "Wife",
                "id": 4,
                "children ": [ ]
              },
              {
                "text": "Company",
                "id": 5,
                "children": [ ]
              }
            ]
          },
          {
            "text": "Program Files",
            "id": 6,
            "children": [
              {
                "text": "intel",
                "id": 7,
                "children": [ ]
              },
              {
                "text": "java",
                "id ": 8,
                "children": [ ]
              }
            ]
          }
        ]
      }
    ]

    代码比较粗糙,性能不好,主要借鉴下思想吧

    回复
    0
  • 取消回复