tree - 利用python如何将无限分类结构的数据,转换成json格式数据。
PHP中文网
PHP中文网 2017-04-18 10:23:45
0
1
1109

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中文网

认证0级讲师

全部回复(1)
巴扎黑
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": [ ]
          }
        ]
      }
    ]
  }
]

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板